Checking if a variable is not nil and not zero in ruby – Dev

The best answers to the question “Checking if a variable is not nil and not zero in ruby” in the category Dev.

QUESTION:

I am using the following code to check if a variable is not nil and not zero

if(discount != nil && discount != 0) 
  ...
end

Is there a better way to do this?

ANSWER:

class Object
  def nil_zero?
    self.nil? || self == 0
  end
end

# which lets you do
nil.nil_zero? # returns true
0.nil_zero?   # returns true
1.nil_zero?   # returns false
"a".nil_zero? # returns false

unless discount.nil_zero?
  # do stuff...
end

Beware of the usual disclaimers… great power/responsibility, monkey patching leading to the dark side etc.

ANSWER:

unless discount.nil? || discount == 0
  # ...
end

ANSWER:

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:

if discount&.nonzero?
  # ...
end

Or postfix:

do_something if discount&.nonzero?

ANSWER:

ok, after 5 years have passed….

if discount.try :nonzero?
  ...
end

It’s important to note that try is defined in the ActiveSupport gem, so it is not available in plain ruby.