Best ruby idiom for "nil or zero"

csexton picture csexton · Oct 16, 2008 · Viewed 68.7k times · Source

I am looking for a concise way to check a value to see if it is nil or zero. Currently I am doing something like:

if (!val || val == 0)
  # Is nil or zero
end

But this seems very clumsy.

Answer

Christian Lescuyer picture Christian Lescuyer · Oct 16, 2008

Objects have a nil? method.

if val.nil? || val == 0
  [do something]
end

Or, for just one instruction:

[do something] if val.nil? || val == 0