.each_key {|a| self[a].strip! if self[a].respond_to? :strip! }
...but it is for a hash, whereas I am trying to do the same with an array.
.each_key {|a| self[a].strip! if self[a].respond_to? :strip! }
...but it is for a hash, whereas I am trying to do the same with an array.
This is what collect is for.
The following handles nil elements by leaving them alone:
yourArray.collect{ |e| e ? e.strip : e }
If there are no nil elements, you may use:
yourArray.collect(&:strip)
...which is short for:
yourArray.collect { |e| e.strip }
strip! behaves similarly, but it converts already "stripped" strings to nil:
[' a', ' b ', 'c ', 'd'].collect(&:strip!)
=> ["a", "b", "c", nil]
If you don't mind first removing nil elements:
YourArray.compact.collect(&:strip)
compact on Array itself. For your answer supply something like a.compact.collect(&:strip) or use yourArray as in Jamie's answer. I know you are going for pseudocode but it is helpful to the questioner to be technically precise.If you are using Rails, consider squish:
Returns the string, first removing all whitespace on both ends of the string, and then changing remaining consecutive whitespace groups into one space each.
yourArray.collect(&:squish)
myArray.collect(&:squish)Adapting the approach you found, from working on a hash to working on an array:
[' c ', 'd', nil, 6, false].each { |a| a.strip! if a.respond_to? :strip! }
=> ["c", "d", nil, 6, false]
puts x[0].class). If it's not a string, you can't use string's strip! method on them.