Best ruby idiom for “nil or zero”

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

    This is very concise:

    if (val || 0) == 0
      # Is nil, false, or zero.
    end
    

    It works as long as you don't mind treating false the same as nil. In the projects I've worked on, that distinction only matters once in a while. The rest of the time I personally prefer to skip .nil? and have slightly shorter code.

    [Update: I don't write this sort of thing any more. It works but is too cryptic. I have tried to set right my misdeeds by changing the few places where I did it.]

    By the way, I didn't use .zero? since this raises an exception if val is, say, a string. But .zero? would be fine if you know that's not the case.

提交回复
热议问题