Best ruby idiom for “nil or zero”

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

    You can use case if you like:

     case val with nil, 0
          # do stuff
     end
    

    Then you can use anything that works with ===, which is nice sometimes. Or do something like this:

    not_valid = nil, 0
    case val1 with *not_valid
          # do stuff
     end
     #do other stuff
     case val2 with *not_valid, false    #Test for values that is nil, 0 or false
          # do other other stuff
     end
    

    It's not exactly good OOP, but it's very flexible and it works. My ifs usually end up as cases anyway.

    Of course Enum.any?/Enum.include? kind of works too ... if you like to get really cryptic:

    if [0, nil].include? val
        #do stuff
    end
    

    The right thing to do is of course to define a method or function. Or, if you have to do the same thing with many values, use a combination of those nice iterators.

提交回复
热议问题