Ruby (Rails): remove whitespace from each array item
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]
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)
If you don't mind first removing nil
elements:
YourArray.compact.collect(&:strip)
https://ruby-doc.org/core/Array.html#method-i-compact
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]
https://ruby-doc.org/core/Array.html#method-i-collect
https://ruby-doc.org/core/String.html#method-i-strip