Best ruby idiom for “nil or zero”

前端 未结 21 2055
日久生厌
日久生厌 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:59

    To be as idiomatic as possible, I'd suggest this.

    if val.nil? or val == 0
        # Do something
    end
    

    Because:

    • It uses the nil? method.
    • It uses the "or" operator, which is preferable to ||.
    • It doesn't use parentheses, which are not necessary in this case. Parentheses should only be used when they serve some purpose, such as overriding the precedence of certain operators.
    0 讨论(0)
  • 2020-12-13 03:59

    Short and clear

    [0, nil].include?(val)

    0 讨论(0)
  • 2020-12-13 03:59

    Shortest and best way should be

    if val&.>(0)
      # do something
    end
    

    For val&.>(0) it returns nil when val is nil since > basically is also a method, nil equal to false in ruby. It return false when val == 0.

    0 讨论(0)
  • 2020-12-13 03:59
    val ||= 0
    if val == 0
    # do something here
    end
    
    0 讨论(0)
  • 2020-12-13 04:00

    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:

    unless val&.nonzero?
      # Is nil or zero
    end
    

    Or postfix:

    do_something unless val&.nonzero?
    
    0 讨论(0)
  • 2020-12-13 04:00

    I deal with this by defining an "is?" method, which I can then implement differently on various classes. So for Array, "is?" means "size>0"; for Fixnum it means "self != 0"; for String it means "self != ''". NilClass, of course, defines "is?" as just returning nil.

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