B Seven
B Seven

Reputation: 45941

What is an idiomatic way to remove false and nil from an Array in Ruby?

I came up with

ary.select{|v| v}

But is there something better?

Upvotes: 2

Views: 1974

Answers (2)

tadman
tadman

Reputation: 211720

You can just delete the values you don't like:

ary - [ nil, false ]

In Ruby 2.2 you can also do this to remove falsey values:

ary.select(&:itself)

Though that's not really shorter.

You can also do:

ary.delete(nil)
ary.delete(false)

Which does in-place modification.

Upvotes: 11

coreyward
coreyward

Reputation: 80128

There's Array#compact, but that'll only remove nil values, or reject if you want to be more explicit about what you're doing here, but otherwise your suggestion is pretty idiomatic.

Upvotes: 2

Related Questions