为什么“真或假"?似乎同时是对与错? [英] Why does "true or true and false" appear to be simultaneously true and false?

查看:144
本文介绍了为什么“真或假"?似乎同时是对与错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到以下信息:

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指南建议在布尔表达式中使用&&||而不是andor的原因之一.正如您期望的那样,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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆