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

前端 未结 18 1644
臣服心动
臣服心动 2020-12-22 15:38

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

相关标签:
18条回答
  • 2020-12-22 16:31

    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
    
    0 讨论(0)
  • 2020-12-22 16:32

    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?
    
    0 讨论(0)
  • 2020-12-22 16:32

    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
    
    0 讨论(0)
  • 2020-12-22 16:33
    unless discount.nil? || discount == 0
      # ...
    end
    
    0 讨论(0)
  • 2020-12-22 16:35
    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.

    0 讨论(0)
  • 2020-12-22 16:36

    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".

    0 讨论(0)
提交回复
热议问题