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

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

还有更好的办法吗?


当前回答

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

其他回答

我相信下面的代码对于ruby代码来说已经足够好了。我不认为我可以写一个单元测试来显示这个和原来的有什么不同。

if discount != 0
end
unless [nil, 0].include?(discount) 
  # ...
end
unless discount.nil? || discount == 0
  # ...
end
if (discount||0) != 0
  #...
end

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

if discount.try :nonzero?
  ...
end

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