我使用下面的代码来检查一个变量是否不为零
if(discount != nil && discount != 0)
...
end
还有更好的办法吗?
我使用下面的代码来检查一个变量是否不为零
if(discount != nil && discount != 0)
...
end
还有更好的办法吗?
当前回答
class Object
def nil_zero?
self.nil? || self == 0
end
end
# which lets you do
nil.nil_zero? # returns true
0.nil_zero? # returns true
1.nil_zero? # returns false
"a".nil_zero? # returns false
unless discount.nil_zero?
# do stuff...
end
当心那些常见的免责声明……巨大的权力/责任,猴子补丁导致黑暗面等等。
其他回答
好的,5年过去了....
if discount.try :nonzero?
...
end
需要注意的是,try是在ActiveSupport宝石中定义的,所以在普通ruby中不可用。
是的,我们有一条干净的红宝石路。
discount.to_f.zero?
这个检查处理了大量的情况,即折扣可能是nil,折扣可能是int 0,折扣可能是浮动0.0,折扣可能是字符串“0.0”,“0”。
您可以将空行转换为整数值并检查零?。
"".to_i.zero? => true
nil.to_i.zero? => 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
从Ruby 2.3.0开始,您可以将安全导航操作符(&.)与数字#非零?结合使用。&。如果实例为nil且非零,则返回nil ?—如果数字为0:
if discount&.nonzero?
# ...
end
或后缀:
do_something if discount&.nonzero?