检查一个变量在ruby中是否不为nil和0

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

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

还有更好的办法吗?

571984 次浏览

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

你可以这样做:

if (!discount.nil? && !discount.zero?)

这里的顺序很重要,因为如果discountnil,那么它将没有zero?方法。Ruby的短路求值应该阻止它尝试求discount.zero?,但是,如果discountnil

unless discount.nil? || discount == 0
# ...
end
unless [nil, 0].include?(discount)
# ...
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

当心那些常见的免责声明……巨大的权力/责任,猴子补丁导致黑暗面等等。

if (discount||0) != 0
#...
end

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

if discount != 0
end
if discount and discount != 0
..
end

更新时,它将false用于discount = false

您可以将空行转换为整数值并检查零?。

"".to_i.zero? => true
nil.to_i.zero? => true

好的,5年过去了....

if discount.try :nonzero?
...
end

值得注意的是,try是在ActiveSupport宝石中定义的,所以它在纯ruby中不可用。

你可以利用NilClass提供的#to_i方法,该方法将为nil值返回0:

unless discount.to_i.zero?
# Code here
end

如果discount可以是小数,你可以使用#to_f来代替,以防止这个数字被舍入为零。

在处理数据库记录时,我喜欢使用迁移帮助器将所有空值初始化为0:

add_column :products, :price, :integer, default: 0

从Ruby 2.3.0开始,你可以结合使用安全导航操作符(&.)和Numeric#nonzero?。如果实例是nil&.返回nil;如果数字是0,返回nonzero?:

if discount&.nonzero?
# ...
end

或后缀:

do_something if discount&.nonzero?
def is_nil_and_zero(data)
data.blank? || data == 0
end

如果我们传递""它将返回false,而空白?返回true。 当data = false时也是如此 空白的吗?对于nil、false、空或空白字符串返回true。 所以用空白更好吗?方法来避免空字符串

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

另一种解决方案是使用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

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

val.to_i.zero?

如果瓦尔nilval.to_i将返回0

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

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

discount.to_f.zero?

此检查处理大量的情况,即折扣可能是nil,折扣可能是int 0,折扣可能是浮动0.0,折扣可能是字符串“;0.0", &;0"”。