我使用下面的代码来检查一个变量是否不为零

if(discount != nil && discount != 0) 
  ...
end

还有更好的办法吗?


当前回答

另一种解决方案是使用Refinements,如下所示:

module Nothingness
  refine Numeric do
    alias_method :nothing?, :zero?
  end

  refine NilClass do
    alias_method :nothing?, :nil?
  end
end

using Nothingness

if discount.nothing?
  # do something
end

其他回答

def is_nil_and_zero(data)
     data.blank? || data == 0 
end  

如果我们传递""它将返回false,而空白?返回true。 当data = false时也是如此 空白的吗?对于nil、false、空或空白字符串返回true。 所以用空白更好吗?方法以避免空字符串。

好的,5年过去了....

if discount.try :nonzero?
  ...
end

需要注意的是,try是在ActiveSupport宝石中定义的,所以在普通ruby中不可用。

if discount and discount != 0
  ..
end

更新,它将为false折扣= false

unless discount.nil? || discount == 0
  # ...
end

你可以这样做:

if (!discount.nil? && !discount.zero?)

这里的顺序很重要,因为如果discount是nil,那么它就不会是0 ?方法。Ruby的短路评估应该阻止它尝试评估折扣。零?,但如果折扣为nil。