bsnvtq
Last Updated: February 25, 2016
·
6.356K
· dperrymorrow
37b092a324da25d53fd63d780692b174

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"]
Say Thanks
Respond

9 Responses
Add your response

2926
Michel funny square

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
37b092a324da25d53fd63d780692b174

@mbillard yes equally elegant, thanks!

over 1 year ago ·
2929
N500718610 1942822 1948441

@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
37b092a324da25d53fd63d780692b174

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

over 1 year ago ·
2931
Michel funny square

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

over 1 year ago ·
2951
86e33dee4a89a8879a26487051c216a8

#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
37b092a324da25d53fd63d780692b174

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

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

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
37b092a324da25d53fd63d780692b174

@realdlee nice, did not know about that method

over 1 year ago ·
Awesome Job

E20ce6a2 ca1f 11e7 82be 7f617c8310c9
SENIOR DEVELOPER (m/w)
·
Berlin, Köln, Hamburg, München
·
Full Time