Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 stuff
end

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 zero
end

Or postfix:

do_something unless val&.nonzero?

First off I think that's about the most concise way you can check for that particular condition.

Second, to me this is a code smell that indicates a potential flaw in your design. Generally nil and zero shouldn't mean the same thing. If possible you should try to eliminate the possibility of val being nil before you hit this code, either by checking that at the beginning of the method or some other mechanism.

You might have a perfectly legitimate reason to do this in which case I think your code is good, but I'd at least consider trying to get rid of the nil check if possible.


You can use the Object.nil? to test for nil specifically (and not get caught up between false and nil). You can monkey-patch a method into Object as well.

class Object
   def nil_or_zero?
     return (self.nil? or self == 0)
   end
end

my_object = MyClass.new
my_object.nil_or_zero?
==> false

This is not recommended as changes to Object are difficult for coworkers to trace, and may make your code unpredictable to others.


nil.to_i returns zero, so I often do this:

val.to_i.zero?

However, you will get an exception if val is ever an object that does not respond_to #to_i.