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

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

其他回答

if (discount||0) != 0
  #...
end
if discount and discount != 0
  ..
end

更新,它将为false折扣= false

unless [nil, 0].include?(discount) 
  # ...
end

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

if discount.try :nonzero?
  ...
end

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

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