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.
。这曾经是我的一个难题。