Best ruby idiom for "nil or zero"

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

But this seems very clumsy.


Objects have a nil? method.

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

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? ||
  # do stuff

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.

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)

my_object =
==> false

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

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

Or postfix:

do_something unless val&.nonzero?

I believe your code is incorrect; it will in fact test for three values: nil, false, and zero. This is because the !val expression is true for all values that are false, which in Ruby is nil and false.

The best I can come up with right now is

if val == nil || val == 0
  # do stuff

Which of course is not very clever, but (very) clear.

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

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

Rails does this via attribute query methods, where in addition to false and nil, 0 and "" also evaluate to false.

if (model.attribute?) # => false if attribute is 0 and model is an ActiveRecord::Base derivation

However it has its share of detractors.

To be as idiomatic as possible, I'd suggest this.

if val.nil? or val == 0
    # Do something


  • It uses the nil? method.
  • It uses the "or" operator, which is preferable to ||.
  • It doesn't use parentheses, which are not necessary in this case. Parentheses should only be used when they serve some purpose, such as overriding the precedence of certain operators.

Shortest and best way should be

if val&.>(0) # do something end

for val&.>(0) it returns nil when val is nil since > basically is also a method, nil equal to false in ruby. it return false when val==0.

Short and clear

[0, nil].include?(val)

I deal with this by defining an "is?" method, which I can then implement differently on various classes. So for Array, "is?" means "size>0"; for Fixnum it means "self != 0"; for String it means "self != ''". NilClass, of course, defines "is?" as just returning nil.

I've just removed my previous answer. I misunderstood you and advised to use #blank? method.

Either way, I would extend Object class and create a method for this purpose.

You can use case if you like:

 case val with nil, 0
      # do stuff

Then you can use anything that works with ===, which is nice sometimes. Or do something like this:

not_valid = nil, 0
case val1 with *not_valid
      # do stuff
 #do other stuff
 case val2 with *not_valid, false    #Test for values that is nil, 0 or false
      # do other other stuff

It's not exactly good OOP, but it's very flexible and it works. My ifs usually end up as cases anyway.

Of course Enum.any?/Enum.include? kind of works too ... if you like to get really cryptic:

if [0, nil].include? val
    #do stuff

The right thing to do is of course to define a method or function. Or, if you have to do the same thing with many values, use a combination of those nice iterators.

I really like Rails blank? method for that kind of things, but it won't return true for 0. So you can add your method:

def nil_zero? 
  if respond_to?(:zero?) 

And it will check if some value is nil or 0:

=> true
=> true
=> false

if val.nil_zero?

Instead of monkey patching a class, you could use refinements starting in Ruby 2.1. Refinements are similar to monkey patching; in that, they allow you to modify the class, but the modification is limited to the scope you wish to use it in.

This is overkill if you want to do this check once, but if you are repeating yourself it's a great alternative to monkey patching.

module NilOrZero
  refine Object do
    def nil_or_zero?
      nil? or zero?

using NilOrZero
class Car
  def initialize(speed: 100)
    puts speed.nil_or_zero?

car =              # false
car = nil)  # true
car = 0)    # true

Refinements were changed in the last minute to be scoped to the file. So earlier examples may have shown this, which will not work.

class Car
  using NilOrZero

This evaluates to true for nil and zero: nil.to_s.to_d == 0

This is very concise:

if (val || 0) == 0
  # Is nil, false, or zero.

It works as long as you don't mind treating false the same as nil. In the projects I've worked on, that distinction only matters once in a while. The rest of the time I personally prefer to skip .nil? and have slightly shorter code.

[Update: I don't write this sort of thing any more. It works but is too cryptic. I have tried to set right my misdeeds by changing the few places where I did it.]

By the way, I didn't use .zero? since this raises an exception if val is, say, a string. But .zero? would be fine if you know that's not the case.

Another solution:

if val.to_i == 0
  # do stuff

val ||= 0
if val == 0
# do something here


 ? where to put freeze_support() in a Python script?
 ? Python idiom for '... if ... else ...' expression
 ? [].append(foo) idiom
 ? Return-if-value idioms (conditional returning)
 ? RuntimeError on windows trying python multiprocessing
 ? Idiom to define a class property
 ? Python, Windows, and Multiprocessing
 ? RuntimeError on windows trying python multiprocessing
 ? "GetOrCreate" - does that idiom have an established name?
 ? What C++ idioms should C++ programmers use?