我使用下面的代码来检查一个变量是否不为零
if(discount != nil && discount != 0)
...
end
还有更好的办法吗?
我使用下面的代码来检查一个变量是否不为零
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.nil? || discount == 0
[do something]
end
if (discount||0) != 0
#...
end
unless [nil, 0].include?(discount) # ... end
在处理数据库记录时,我喜欢使用迁移帮助器将所有空值初始化为0:
add_column :products, :price, :integer, default: 0
if discount and discount != 0
..
end
更新,它将为false折扣= false