Best ruby idiom for “nil or zero”

前端 未结 21 2057
日久生厌
日久生厌 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 04:06

    Objects have a nil? method.

    if val.nil? || val == 0
      [do something]
    end
    

    Or, for just one instruction:

    [do something] if val.nil? || val == 0
    
    0 讨论(0)
  • 2020-12-13 04:06

    You can use the Object.nil? to test for nil specifically (and not get caught up between false and nil). You can monkey-patch a method into Object as well.

    class Object
       def nil_or_zero?
         return (self.nil? or self == 0)
       end
    end
    
    my_object = MyClass.new
    my_object.nil_or_zero?
    ==> false
    

    This is not recommended as changes to Object are difficult for coworkers to trace, and may make your code unpredictable to others.

    0 讨论(0)
  • 2020-12-13 04:09
    unless (val || 0).zero?
    
        # do stufff
    
    end
    
    0 讨论(0)
提交回复
热议问题