Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check nil on multiple variables

Tags:

null

ruby

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?

like image 229
massaskillz Avatar asked Apr 08 '16 21:04

massaskillz


1 Answers

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

like image 108
zetetic Avatar answered Sep 25 '22 01:09

zetetic