“或"与“或"之间的差异.和||在Ruby中? [英] Difference between "or" and || in Ruby?
问题描述
Ruby中的or
和||
运算符有什么区别?还是只是偏爱?
What's the difference between the or
and ||
operators in Ruby? Or is it just preference?
推荐答案
这是运算符优先级的问题.
It's a matter of operator precedence.
||
的优先级高于or
.
因此,在这两者之间,您还有其他运算符,包括三元运算符(? :
)和赋值运算符(=
),因此您选择的哪个运算符会影响语句的结果.
So, in between the two you have other operators including ternary (? :
) and assignment (=
) so which one you choose can affect the outcome of statements.
这是 ruby运算符优先级表.
有关使用and
/&&
的另一个示例,请参见此问题.
See this question for another example using and
/&&
.
另外,请注意可能发生的一些令人讨厌的事情:
Also, be aware of some nasty things that could happen:
a = false || true #=> true
a #=> true
a = false or true #=> true
a #=> false
前两个语句的求值结果均为true
,但是第二个语句将a
设置为false
,因为=
优先级低于||
但高于or
.
Both of the previous two statements evaluate to true
, but the second sets a
to false
since =
precedence is lower than ||
but higher than or
.
这篇关于“或"与“或"之间的差异.和||在Ruby中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!