Reputation: 283
A lot of variables require some processing, so I'm checking if any of them are nil
. Is there a more efficient way of writing the following?
unless a.nil? || b.nil? || c.nil? || d.nil? || e.nil? || f.nil? || g.nil?
render 'view'
end
Or should I avoid checking a lot of variables for nil
on one line?
Upvotes: 5
Views: 5238
Reputation: 47578
By using none?
you can have if
instead of unless
:
if [a,b,c,d,e,f,g].none?(&:nil?)
Come to think of it, this can be reduced to simply:
if [a,b,c,d,e,f,g].all?
if you don't mind treating false
the same as nil
Is there a more efficient way of writing the following?
I think a better question is, "Is there a more expressive way of writing..."
Upvotes: 8
Reputation: 3900
If your a,b,c...
are objects (or something that is never false
) you can write it like this:
if a && b && c && d && e && f
render 'view'
end
Upvotes: 2
Reputation: 13487
render 'view' unless [a,b,c,d,e,f,g].any?(&:nil?)
Another way:
render 'view' if [a,b,c,d,e,f,g].index(nil)
Upvotes: 3
Reputation: 3298
Also some other method:
arr = [a,b,c,d,e,f,g]
render 'view' if arr.compact == arr
Upvotes: 2