Reject empty items from an array in Ruby
Recently I needed to clear an array of empty items in Ruby. I discovered this great way to achieve the task.
puts ["foo", "bar", ""] - [""]
#=> ["foo", "bar"]
Written by David Morrow
Related protips
9 Responses
I just use
["foo", "bar", ""].reject(&:blank?)
but I guess it won't work if the array contains items other than strings.
@mbillard yes equally elegant, thanks!
@mbillard blank? is a Rails thing, not a core ruby thing.
["foo", "bar", "", nil].compact.reject(&:empty?)
does the right thing in situations where ActiveSupport isn't available.
@sandersch I like you solution as it rejects empty strings and also nil
@sandersch true, I never use Ruby alone so I don't always make the distinction between both.
#empty?
only works on String though, something more general but slightly more expensive is this:
a = [1, "foo", nil, :bar]
a.reject!{|e| e.nil? || e.to_s.empty? }
p a # => [1, "foo", :bar]
or you could add anything you wanted to the reject array like in my example...
["foo", "", nil] - ["", nil]
# => ["foo"]
Also worth considering delete_if:
["foo", "", "bar"].delete_if(&:empty?)
delete_if and reject are similar but reject returns nil if nothing is rejected (which has made a difference to me in the past)
@realdlee nice, did not know about that method