Best ruby idiom for "nil or zero"
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
If you really like method names with question marks at the end:
if val.nil? || val.zero? # do stuffend
Your solution is fine, as are a few of the other solutions.
Ruby can make you search for a pretty way to do everything, if you're not careful.
From Ruby 2.3.0 onward, you can combine the safe navigation operator (&.
) with Numeric#nonzero?
. &.
returns nil
if the instance was nil
and nonzero?
- if the number was 0
:
unless val&.nonzero? # Is nil or zeroend
Or postfix:
do_something unless val&.nonzero?