我在Ruby中的i = true和false是真的吗?

ale*_*lex 13 ruby

我在这里从根本上误解了Ruby吗?我已经写了大约2年的Ruby代码了,就在今天偶然发现了......

ruby-1.8.7-p249 > i = true and false
 => false 
ruby-1.8.7-p249 > i
 => true 
Run Code Online (Sandbox Code Playgroud)

有人能解释一下这里发生了什么吗?我确定这是规格,但这对我来说似乎有点直观......

Tho*_*mas 30

运营商&&and具有不同的优先级,并且=恰好之间是英寸

irb(main):006:0> i = true and false
=> false
irb(main):007:0> i
=> true
irb(main):008:0> i = true && false
=> false
irb(main):009:0> i
=> false
irb(main):010:0> 
Run Code Online (Sandbox Code Playgroud)

第一个是读(i = true) and false,第二个是i = (true && false).

  • 这是Ruby语言的奇怪怪癖.昨天,在我学习Ruby的第一天,我在"Ruby for Python程序员"文章中遇到了这个警告:) (3认同)

sep*_*p2k 13

and具有较低的优先级比=,以便i = true and false被解析为(i = true) and false.

因此true赋值给该值i,然后该操作的返回值(这是真的)and用false编辑,这导致整个表达式评估为false,即使i仍然具有该值true.