Best ruby idiom for “nil or zero”

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

    My solution also use Refinements, minus the conditionals.

    module Nothingness
      refine Numeric do
        alias_method :nothing?, :zero?
      end
    
      refine NilClass do
        alias_method :nothing?, :nil?
      end
    end
    
    using Nothingness
    
    if val.nothing?
      # Do something
    end
    

提交回复
热议问题