Ruby 中的 Nil 和布尔值 [英] Nil and boolean in Ruby
问题描述
有人可以解释一下原因吗?刚刚花了 30 分钟试图弄清楚为什么我的布尔方法返回 nil
并在 Ruby 中发现了这一点:
Can someone explain the reasoning being this? Just spent 30 mins trying to figure out why my boolean method returned nil
and found out that in Ruby:
2.2.1 :001 > nil && true
=> nil
2.2.1 :002 > nil && false
=> nil
由于 nil
是一个假值,我本来期望 nil && 的输出真
为假.似乎也违背了条件运算符应该返回布尔值的想法.
Since nil
is a falsey value, I would have expected the output of nil && true
to be false. Also it seems to go against the idea that conditional operators should return a boolean value.
这背后的原理是什么?
布尔运算符不可交换是有道理的:
It makes sense that the boolean operator is not commutative:
nil && false != false && nil
对于看到这一点的其他人,我的问题是在 Rails 中我有如下声明:
For others seeing this, my issue was that in rails I had a statement like:
def some_method?
object.attr && object.attr > something
end
但是当 object.attr
为 nil 时,函数将为 nil.在大多数情况下这很好,但是当将布尔方法链接在一起时,就没有那么多了.我只是把它改成了这个:
But when object.attr
is nil, the function will be nil. Which is fine in most cases but when chaining boolean methods together, not so much. I just changed it to this instead:
def some_method?
object.attr.present? && object.attr > something
end
我可以在 vanilla Ruby 中做同样的事情:
I could do the same thing in vanilla Ruby with:
def some_method?
!!object.attr && object.attr > something
end
推荐答案
该语句按顺序遍历条件,得到假结果时停止并返回上次执行的求值的值.
The statement goes through the conditions in order, will stop when a falsy result is obtained and return the value of the last evaluation performed.
与 &&
不同的是,||
会停在一个真值处.
In contrary to &&
which stops at a falsy value, ||
will stop at a truthy value instead.
这篇关于Ruby 中的 Nil 和布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!