How do I remove blank elements from an array? How do I remove blank elements from an array? ruby ruby

How do I remove blank elements from an array?


There are many ways to do this, one is reject

noEmptyCities = cities.reject { |c| c.empty? }

You can also use reject!, which will modify cities in place. It will either return cities as its return value if it rejected something, or nil if no rejections are made. That can be a gotcha if you're not careful (thanks to ninja08 for pointing this out in the comments).


1.9.3p194 :001 > ["", "A", "B", "C", ""].reject(&:empty?)=> ["A", "B", "C"]


Here is what works for me:

[1, "", 2, "hello", nil].reject(&:blank?)

output:

[1, 2, "hello"]