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

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

提交回复
热议问题