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

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

还有更好的办法吗?


当前回答

你可以利用NilClass提供的#to_i方法,它将为nil值返回零:

unless discount.to_i.zero?
  # Code here
end

如果折扣可以是小数,则可以使用#to_f来代替,以防止数字四舍五入为零。

其他回答

if discount.nil? || discount == 0
  [do something]
end
unless discount.nil? || discount == 0
  # ...
end

你可以这样做:

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

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

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

if discount.try :nonzero?
  ...
end

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

另一种解决方案是使用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