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

前端 未结 18 1643
臣服心动
臣服心动 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:26

    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.

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

    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.

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

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

    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.

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

    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.

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

    You can convert your empty row to integer value and check zero?.

    "".to_i.zero? => true
    nil.to_i.zero? => true
    
    0 讨论(0)
提交回复
热议问题