> true 而我也得到: if true or true and false puts "that's true!-6ren">
gpt4 book ai didi

ruby - 为什么 "true or true and false"看起来同时为真和假?

转载 作者:数据小太阳 更新时间:2023-10-29 07:21:56 26 4
gpt4 key购买 nike

我得到以下信息:

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 或 true and false 同时是 truefalse(就像薛定谔的猫)?

最佳答案

这与优先级有关。 puts true or true and false 实际上计算为 (puts true) or (true and false) [编辑:不完全是。请参阅下面 Todd 的注释。],并且 if true or true and false 计算为 if (true or (true and false))。这是由于 puts(一种方法)和 if(一种语言关键字)相对于表达式的其他项的优先级。

当你评估 puts true 或 true and false 时,你会在 irb 中看到 => false(记住,那是 (puts true) or (true and false) ) 因为 puts 输出 true 并返回 nil,这是错误的,导致 (true and false) 将被评估,它返回 false

这就是为什么大多数 Ruby 指南推荐使用 &&|| 而不是 andor 的原因之一在 bool 表达式中。 设置为真 || true && false 计算为 puts (true || (true && false))if true || true && false 的计算结果为 if (true || (true && false)),正如您所期望的那样。

关于ruby - 为什么 "true or true and false"看起来同时为真和假?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51992245/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com