bsnvtq
Last Updated: February 25, 2016
·
9.447K
· 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

2926

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 ·
2927

@mbillard yes equally elegant, thanks!

over 1 year ago ·
2929

@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 ·
2930

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

over 1 year ago ·
2931

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

over 1 year ago ·
2951

#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 ·
2960

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

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

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 ·
6564

@realdlee nice, did not know about that method

over 1 year ago ·