为什么“真或假"?似乎同时是对与错? [英] Why does "true or true and false" appear to be simultaneously true and false?
问题描述
我得到以下信息:
puts true or true and false
# >> true
我也得到了:
if true or true and false
puts "that's true!"
else
puts "that's false!"
end
# >> that's false!
为什么true or true and false
既是true
又是false
(如薛定的猫)?
Why is true or true and false
both true
and false
(like Schrödinger's cat)?
推荐答案
它与优先级有关. puts true or true and false
实际上评估为(puts true) or (true and false)
,if true or true and false
的评估结果为if (true or (true and false))
.这是由于puts
(一种方法)和if
(一种语言关键字)相对于表达式的其他术语的优先级.
It has to do with precedence. puts true or true and false
actually evaluates as (puts true) or (true and false)
, and if true or true and false
evaluates as if (true or (true and false))
. This is due to the precedences of puts
(a method) and if
(a language keyword) relative to the other terms of the expression.
当您评估puts true or true and false
时,您会在irb中看到=> false
(记住,这是(puts true) or (true and false)
),因为puts
输出true
并返回nil
,这是错误的,导致对(true and false)
进行评估接下来,返回false
.
You see => false
in irb when you evaluate puts true or true and false
(remember, that's (puts true) or (true and false)
) because puts
outputs true
and returns nil
, which is falsey, causing the (true and false)
to be evaluated next, which returns false
.
这是大多数Ruby指南建议在布尔表达式中使用&&
和||
而不是and
和or
的原因之一.正如您期望的那样,puts true || true && false
的评估结果为puts (true || (true && false))
,而if true || true && false
的评估结果为if (true || (true && false))
.
This is one reason why most Ruby guides recommend using &&
and ||
instead of and
and or
in boolean expressions. puts true || true && false
evaluates as puts (true || (true && false))
and if true || true && false
evaluates as if (true || (true && false))
, both as you'd expect them to.
这篇关于为什么“真或假"?似乎同时是对与错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!