Ruby (Rails): remove whitespace from each array item

Viewed 35539

I found this code:

.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.

4 Answers

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)
Related