I am using the following code to check if a variable is not nil and not zero
if(discount != nil && discount != 0)
...
end
Is the
You can take advantage of the NilClass
provided #to_i
method, which will return zero for nil
values:
unless discount.to_i.zero?
# Code here
end
If discount
can be fractional numbers, you can use #to_f
instead, to prevent the number from being rounded to zero.
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.
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.
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
.
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.
You can convert your empty row to integer value and check zero?.
"".to_i.zero? => true
nil.to_i.zero? => true