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

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

还有更好的办法吗?


当前回答

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

其他回答

在处理数据库记录时,我喜欢使用迁移帮助器将所有空值初始化为0:

add_column :products, :price, :integer, default: 0
if (discount||0) != 0
  #...
end

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

另一种解决方案是使用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.nil? && !discount.zero?)

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