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

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

还有更好的办法吗?


当前回答

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

unless discount.to_i.zero?
  # Code here
end

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

其他回答

if discount and discount != 0
  ..
end

更新,它将为false折扣= false

你可以把discount初始化为0,只要你的代码保证在初始化之前不尝试使用它。我想这只会删除一张支票,我想不出还有什么。

if (discount||0) != 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

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

unless discount.to_i.zero?
  # Code here
end

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