Reputation: 7138
Ruby compacts the sequence only if it has nil value, how do I compact "" empty value
Upvotes: 1
Views: 319
Reputation: 66837
I know this has no Ruby on Rails tag, but should you be using the framework, the best solution IMHO is:
a = [1, nil, 2, '', 3]
a.select(&:present?)
#=> [1, 2, 3]
In plain Ruby I'd go with Sergio's answer or a.select { |x| x.empty? || x.nil? }
if the array can only contain String
s and nil
s.
Upvotes: 3
Reputation: 230296
Something like this:
a = [1, nil, 2, '', 3]
a.reject{|x| x == '' || x.nil?} # => [1, 2, 3]
Upvotes: 7
Reputation: 61512
A similar way of doing it to Sergio's:
irb(main):006:0> a = [1,nil,2,''] => [1, nil, 2, ""]
irb(main):007:0> a.reject!{|x| x.nil? || x == ''} => [1, 2]
Upvotes: 3