Check nil for a few variables

A lot of variables require some processing, so I check to see if there is any of them nil. Is there a more efficient way to write 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 for multiple variables for nilon a single line?

+4
source share
5 answers

Using none?, you can have ifinstead unless:

if [a,b,c,d,e,f,g].none?(&:nil?)

Think about it, it can be reduced to a simple:

if [a,b,c,d,e,f,g].all?

if you don't mind processing falsejust likenil

Is there a more efficient way to write the following?

I think the best question is: "Is there a more expressive way to write ..."

+6
source
unless [a,b,c,d,e,f,g].include?(nil)
  render 'view'
end
+7
render 'view' unless [a,b,c,d,e,f,g].any?(&:nil?)

:

render 'view' if [a,b,c,d,e,f,g].index(nil)
+2

:

arr = [a,b,c,d,e,f,g]
render 'view' if arr.compact == arr
+2

If yours a,b,c...is objects (or something that is never false), you can write it like this:

if a && b && c && d && e && f
    render 'view' 
end
+2
source

All Articles