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
Add your response
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
·
@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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Related Tags
#ruby
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#