tags:

views:

6639

answers:

8

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?

A: 

You could initialize discount to 0 as long as your code is guaranteed not to try and use it before it is initialized. That would remove one check I suppose, I can't think of anything else.

Ed Swangren
+5  A: 

Isn't this the same question as Best ruby idiom for nil or zero?

Kevin
Isn't it the opposite of that question?
David Moles
A: 

You could do this:

if (!discount.nil? && !discount.zero?)

The order is important here, because if discount is nil, then it will not have a zero? method. Ruby's short-circuit evaluation should prevent it from trying to evaluate discount.zero?, however, if discount is nil.

yjerem
+5  A: 
unless discount.nil? || discount == 0
  # ...
end
Dejan Simic
Use 'or' instead of ||
Orion Edwards
A: 
unless [nil, 0].include?(discount) 
  # ...
end
Dejan Simic
+4  A: 
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.

madlep
Love it. So Ruby-esque... and clear.
Atømix
A: 
if (discount||0) != 0
  #...
end
Raimonds Simanovskis
A: 

I believe the following is good enough for ruby code. I don't thin I could write a unit test that showed any difference between this and the original.

if discount != 0

end

Jeff Waltzer