.each_key {|a| self[a].strip! if self[a].respond_to? :strip! }
...但是它是用于哈希表的,而我正在尝试使用数组做同样的事情。
.each_key {|a| self[a].strip! if self[a].respond_to? :strip! }
...但是它是用于哈希表的,而我正在尝试使用数组做同样的事情。
这就是collect
的用途。
以下处理nil
元素,通过让它们保持不变:
yourArray.collect{ |e| e ? e.strip : e }
如果没有nil
元素,你可以使用:
yourArray.collect(&:strip)
...which is short for:
这句话的意思是:「简称为:」yourArray.collect { |e| e.strip }
strip!
的行为类似,但是它会将已经被"剥离"的字符串转换为nil
:
[' a', ' b ', 'c ', 'd'].collect(&:strip!)
=> ["a", "b", "c", nil]
如果您不介意首先删除nil
元素:
YourArray.compact.collect(&:strip)
Array
本身上调用 compact
。对于您的答案,请提供类似于 a.compact.collect(&:strip)
的内容,或者使用像 Jamie 的答案中的 yourArray
。我知道您正在进行伪代码编写,但在技术上精确方面对提问者有帮助。 - Ray ToalmyArray.collect(&:squish)
。 - Toby Joiner根据您找到的方法,从操作哈希表转变为操作数组:
[' c ', 'd', nil, 6, false].each { |a| a.strip! if a.respond_to? :strip! }
=> ["c", "d", nil, 6, false]
puts x [0] .class
)。如果不是字符串,则无法在它们上使用字符串的 strip!
方法。 - Nikita Rybak
.strip
不应该返回nil
。然而,如果没有剥离任何东西,.strip!
的确会返回nil
。我可以在交互式 shell(irb)中确认这一点。 - pronebird|| x
吗? - maahd