问题描述
我想知道为什么ruby给and
,or
的优先级低于&&
,||
并分配运算符?有什么理由吗?
I wonder why ruby give and
, or
less precedence than &&
, ||
, and assign operator? Is there any reason?
推荐答案
我的猜测是,这直接来自Perl.在特定情况下,需要较低优先级的情况下,在Perl 5中后来添加了or
和and
运算符.
My guess is that's a direct carry-over from Perl. The operators or
and and
were added later in Perl 5 for specific situations were lower precedence was desired.
例如,在Perl中,我们希望||
具有较低的优先级,以便我们可以编写:
For example, in Perl, here we wish that ||
had lower precedence, so that we could write:
try to perform big long hairy complicated action || die ;
,并确保||
不会吞噬动作的一部分.正是出于这个目的,Perl 5引入了or
,这是||
的新版本,它的优先级较低.
and be sure that the ||
was not going to gobble up part of the action. Perl 5 introduced or
, a new version of ||
that has low precedence, for exactly this purpose.
在Ruby中可以使用or
但不能使用||
的示例:
An example in Ruby where you could use or
but not ||
:
value = possibly_false or raise "foo"
如果使用||
,则可能是语法错误.
If you used ||
, it would be a syntax error.
这篇关于在“和",“或"后面是否有任何智慧? Ruby中的运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!