Remove nil and blank string in an array in Ruby

You could do this:

arr.reject { |e| e.to_s.empty? } #=> [1, 2, "s", "d"]

Note nil.to_s => ''.


Since you want to remove both nil and empty strings, it's not a duplicate of How do I remove blank elements from an array?

You want to use .reject:

arr = [1, 2, 's', nil, '', 'd']
arr.reject { |item| item.nil? || item == '' }

NOTE: reject with and without bang behaves the same way as compact with and without bang: reject! and compact! modify the array itself while reject and compact return a copy of the array and leave the original intact.

If you're using Rails, you can also use blank?. It was specifically designed to work on nil, so the method call becomes:

arr.reject { |item| item.blank? }

Tags:

Arrays

Ruby