Reputation: 5220
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
Reputation: 392
I believe you can now use the safe navigation operator:
if foo&.any?
Upvotes: 2
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