Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?.

like image 763
chug2k Avatar asked Mar 20 '12 18:03

chug2k


2 Answers

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.

like image 76
Niklas B. Avatar answered Sep 27 '22 18:09

Niklas B.


I believe you can now use the safe navigation operator:

if foo&.any?
like image 44
abdul ahmad Avatar answered Sep 27 '22 20:09

abdul ahmad