Ruby 设置变量时或与| |之间的差异

Ruby 设置变量时或与| |之间的差异,ruby,Ruby,我觉得|和或是同义词 设置带有或的变量不保持值;为什么? >> test = nil or true => true >> test => nil >> test = false or true => true >> test => false 与| >> test = nil || true => true >> test => true 或的优先级低于= test = nil o

我觉得
|
是同义词

设置带有
的变量不保持值;为什么?

>> test = nil or true
=> true
>> test
=> nil

>> test = false or true
=> true
>> test
=> false
|

>> test = nil || true
=> true
>> test
=> true
的优先级低于
=

test = nil or true
test = nil || true

(test = nil) or true
test = (nil || true)
这是
true
,同时将
test
设置为
nil

|
的优先级高于
=

test = nil or true
test = nil || true

(test = nil) or true
test = (nil || true)

这是
true
,同时将
test
设置为
true
&
之间相同。有一次我被这个问题困扰,然后我意识到虽然
&
更可读,但这并不意味着它总是更合适

>> f = true && false
=> false
>> f
=> false
>> f = true and false
=> false
>> f
=> true
>> 

…这就是为什么我们不会编写这样的代码,或者如果我们这样做了,我们总是会使用括号来说明发生了什么。谢谢,这非常有意义。
|
不仅具有非常高的优先级和
非常低的优先级,而且
具有相同的优先级,而
|
&&
有不同的先例。通常,在条件表达式中,始终使用运算符形式,因为它们具有您实际期望的相对优先顺序。仅对控制流使用
,您实际上希望“内部”表达式绑定得更紧。类似于
test=blah.get_records或put'No records found.
。这曾经是我的一个难题。