我使用下面的代码来检查一个变量是否不为零
if(discount != nil && discount != 0)
...
end
还有更好的办法吗?
我使用下面的代码来检查一个变量是否不为零
if(discount != nil && discount != 0)
...
end
还有更好的办法吗?
当前回答
unless [nil, 0].include?(discount) # ... end
其他回答
unless [nil, 0].include?(discount) # ... end
unless discount.nil? || discount == 0 # ... end
def is_nil_and_zero(data)
data.blank? || data == 0
end
如果我们传递""它将返回false,而空白?返回true。 当data = false时也是如此 空白的吗?对于nil、false、空或空白字符串返回true。 所以用空白更好吗?方法以避免空字符串。
另一种解决方案是使用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