Best ruby idiom for “nil or zero”

前端 未结 21 2105
日久生厌
日久生厌 2020-12-13 03:04

I am looking for a concise way to check a value to see if it is nil or zero. Currently I am doing something like:

if (!val || val == 0)
  # Is nil or zero
e         


        
21条回答
  •  感情败类
    2020-12-13 03:46

    I really like Rails blank? method for that kind of things, but it won't return true for 0. So you can add your method:

    def nil_zero? 
      if respond_to?(:zero?) 
        zero? 
      else 
        !self 
      end 
    end 
    

    And it will check if some value is nil or 0:

    nil.nil_zero?
    => true
    0.nil_zero?
    => true
    10.nil_zero?
    => false
    
    if val.nil_zero?
      #...
    end
    

提交回复
热议问题