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

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

还有更好的办法吗?


当前回答

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

其他回答

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

if discount != 0
end

从Ruby 2.3.0开始,您可以将安全导航操作符(&.)与数字#非零?结合使用。&。如果实例为nil且非零,则返回nil ?—如果数字为0:

if discount&.nonzero?
  # ...
end

或后缀:

do_something if discount&.nonzero?

另一种解决方案是使用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 and discount != 0
  ..
end

更新,它将为false折扣= false

if discount.nil? || discount == 0
  [do something]
end