Best ruby idiom for “nil or zero”

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

    I believe your code is incorrect; it will in fact test for three values: nil, false, and zero. This is because the !val expression is true for all values that are false, which in Ruby is nil and false.

    The best I can come up with right now is

    if val == nil || val == 0
      # do stuff
    end
    

    Which of course is not very clever, but (very) clear.

提交回复
热议问题