diya
diya

Reputation: 7138

How to compact empty elements in an array

Ruby compacts the sequence only if it has nil value, how do I compact "" empty value

Upvotes: 1

Views: 319

Answers (3)

Michael Kohl
Michael Kohl

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 Strings and nils.

Upvotes: 3

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230296

Something like this:

a = [1, nil, 2, '', 3]
a.reject{|x| x == '' || x.nil?} # => [1, 2, 3]

Upvotes: 7

Hunter McMillen
Hunter McMillen

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

Related Questions