我使用下面的代码来检查一个变量是否不为零
if(discount != nil && discount != 0)
...
end
还有更好的办法吗?
我使用下面的代码来检查一个变量是否不为零
if(discount != nil && discount != 0)
...
end
还有更好的办法吗?
当前回答
是的,我们有一条干净的红宝石路。
discount.to_f.zero?
这个检查处理了大量的情况,即折扣可能是nil,折扣可能是int 0,折扣可能是浮动0.0,折扣可能是字符串“0.0”,“0”。
其他回答
if (discount||0) != 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
当心那些常见的免责声明……巨大的权力/责任,猴子补丁导致黑暗面等等。
我相信下面的代码对于ruby代码来说已经足够好了。我不认为我可以写一个单元测试来显示这个和原来的有什么不同。
if discount != 0
end
if discount.nil? || discount == 0
[do something]
end
你可以利用NilClass提供的#to_i方法,它将为nil值返回零:
unless discount.to_i.zero?
# Code here
end
如果折扣可以是小数,则可以使用#to_f来代替,以防止数字四舍五入为零。