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
Alternative solution is to use Refinements, like so:
module Nothingness
refine Numeric do
alias_method :nothing?, :zero?
end
refine NilClass do
alias_method :nothing?, :nil?
end
end
using Nothingness
if discount.nothing?
# do something
end
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?
I believe the following is good enough for ruby code. I don't think I could write a unit test that shows any difference between this and the original.
if discount != 0
end
unless discount.nil? || discount == 0 # ... end
def is_nil_and_zero(data)
data.blank? || data == 0
end
If we pass "" it will return false whereas blank? returns true. Same is the case when data = false blank? returns true for nil, false, empty, or a whitespace string. So it's better to use blank? method to avoid empty string as well.
Yes, we do have a clean way in ruby.
discount.to_f.zero?
This check handles good amount of cases i.e. discount may be nil, discount may be int 0, discount may be float 0.0, discount may be string "0.0", "0".