chug2k
chug2k

Reputation: 5220

Rails idiom for .present? and .any?

Is there a Rails/Ruby idiom for checking if an enumerable is both present and has non-nil values?

I get errors if I ever try to do nil.any? so I always have to do if foo && foo.any?.

Upvotes: 8

Views: 3915

Answers (3)

abdul ahmad
abdul ahmad

Reputation: 392

I believe you can now use the safe navigation operator:

if foo&.any?

Upvotes: 2

Dave Newton
Dave Newton

Reputation: 160211

You could also use the andand gem:

foo.andand.any?

Upvotes: 0

Niklas B.
Niklas B.

Reputation: 95318

You can use the try method provided by ActiveSupport:

obj.try(:any?)

This will evaluate to nil if obj.nil? or to false if obj is an empty collection, so in both cases it will evaluate to a falsy value in a boolean context.

Upvotes: 11

Related Questions