和和之间的区别||设置变量时

时间:2021-05-14 23:10:13

I was under the impression that || and or were synonymous.

我的印象是||或者是同义词。

Setting variable with or does not hold value; why?

设置变量有或没有值;为什么?

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

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

Works 'as expected' with ||

使用||“按预期”工作

>> test = nil || true
=> true
>> test
=> true

2 个解决方案

#1


15  

or has lower precedence than =.

或者优先于=。

test = nil or true

is the same as

是相同的

(test = nil) or true

which is true, while setting test to nil.

这是真的,同时将测试设置为零。

|| has higher precedence than =.

||优先级高于=。

test = nil || true

is the same as

是相同的

test = (nil || true)

which is true, while setting test to true.

这是真的,同时将test设置为true。

#2


1  

Same between and and &&. I was once bited by this gotcha, then I realize that although and is more readable than &&, that does not mean it always more suitable.

和和之间相同。我曾经被这个问题所困扰,然后我意识到虽然并且比&&更具可读性,但这并不意味着它总是更合适。

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

#1


15  

or has lower precedence than =.

或者优先于=。

test = nil or true

is the same as

是相同的

(test = nil) or true

which is true, while setting test to nil.

这是真的,同时将测试设置为零。

|| has higher precedence than =.

||优先级高于=。

test = nil || true

is the same as

是相同的

test = (nil || true)

which is true, while setting test to true.

这是真的,同时将test设置为true。

#2


1  

Same between and and &&. I was once bited by this gotcha, then I realize that although and is more readable than &&, that does not mean it always more suitable.

和和之间相同。我曾经被这个问题所困扰,然后我意识到虽然并且比&&更具可读性,但这并不意味着它总是更合适。

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