Last Updated: February 25, 2016
·
13.55K
· dperrymorrow

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"]

9 Responses
Add your response

I just use

["foo", "bar", ""].reject(&:blank?)

but I guess it won't work if the array contains items other than strings.

over 1 year ago ·

@mbillard yes equally elegant, thanks!

over 1 year ago ·

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

over 1 year ago ·

@sandersch I like you solution as it rejects empty strings and also nil

over 1 year ago ·

@sandersch true, I never use Ruby alone so I don't always make the distinction between both.

over 1 year ago ·

#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]
over 1 year ago ·

or you could add anything you wanted to the reject array like in my example...

["foo", "", nil] - ["", nil]
# => ["foo"]
over 1 year ago ·

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)

over 1 year ago ·

@realdlee nice, did not know about that method

over 1 year ago ·