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

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

还有更好的办法吗?


当前回答

是的,我们有一条干净的红宝石路。

discount.to_f.zero?

这个检查处理了大量的情况,即折扣可能是nil,折扣可能是int 0,折扣可能是浮动0.0,折扣可能是字符串“0.0”,“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 == 0
  [do something]
end
if (discount||0) != 0
  #...
end

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

我更喜欢使用更简洁的方法:

val.to_i.zero?

如果val为nil, val.to_i将返回0,

在此之后,我们所需要做的就是检查最终值是否为零。