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

ID : 10444

viewed : 79

Tags : rubyruby

Top 5 Answer for Checking if a variable is not nil and not zero in ruby

vote vote

99

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

90

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.

vote vote

76

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.

vote vote

66

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? 
vote vote

53

 unless [nil, 0].include?(discount)    # ... end 

Top 3 video Explaining Checking if a variable is not nil and not zero in ruby

Related QUESTION?