简体   繁体   English

ruby中的false && nil和nil && false

[英]false && nil and nil && false in ruby

Why does nil && false return nil while false && nil returns false ? 为什么nil && false返回nilfalse && nil返回false

I read the top answer in nil || 我在nil ||中读到了最佳答案 false and false || 假和假|| nil in ruby . 在红宝石中没有 It seems to me that both nil and false evaluate as falsy value, but why do these two expressions return different values? 在我看来, nilfalse评估为falsy值,但为什么这两个表达式返回不同的值?

The rule is simple: && returns its first argument if it is falsy. 规则很简单:如果它是假的, &&返回它的第一个参数。 Otherwise, it evaluate and returns its second argument. 否则,它会评估并返回其第二个参数。

So in 所以

nil && false

and

false && nil

In both cases, the first argument is falsy. 在这两种情况下,第一个参数都是假的。 nil and false are the only two values that evaluate falsy), so the result of the expression is the first argument. nilfalse是评估falsy的唯一两个值),因此表达式的结果是第一个参数。

The fact that the second argument also happens to be false doesn't matter. 第二个参数也恰好是假的事实并不重要。 In fact, the second argument isn't evaluated because of short-circuit. 实际上,由于短路,第二个参数未被评估。

It's about operations order. 这是关于运营秩序。 Nil doesn't have a boolean value. Nil没有布尔值。 In && statement it returns false when at least on argument is false. 在&&语句中,当至少在参数为false时,它返回false。

So in the expression: false && nil it is discovering that the first argument is false and there is pointless to check the second one, so it returned false. 所以在表达式中: false && nil它发现第一个参数是假的,并且检查第二个参数是没有意义的,所以它返回false。 In second case - nil && false it encounters nil, so the value which cannot be compare with boolean, in consequence the expression cannot be evaluated, so it returns 'nil', like in every other similar case in ruby. 在第二种情况下 - nil && false它会遇到nil,因此无法与boolean进行比较的值,因此无法计算表达式,因此它返回'nil',就像在ruby中的其他类似情况一样。

In '||' 在'||' statement it gives false where first or second argument is false. 声明它在第一个或第二个参数为假的情况下给出错误。

1st case: false || nil 第一种情况: false || nil false || nil - it checks that first argument is false and then verifies second one which actually is nothing, so that it gives first value. false || nil - 它检查第一个参数是否为假,然后验证第二个实际上什么都没有,以便它给出第一个值。

2nd case nil || false 第二种情况nil || false nil || false it checks first is nothing, then second which is boolean so it returns false. nil || false它首先检查是什么,然后第二个是布尔值,所以它返回false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM