“和”、“或”背后有什么智慧吗? Ruby 中的运算符?
我想知道为什么 ruby 的 and
、 or
优先级低于 &&
、 ||
和赋值运算符?有什么理由吗?
I wonder why ruby give and
, or
less precedence than &&
, ||
, and assign operator? Is there any reason?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我的猜测是这是 Perl 的直接继承。运算符
or
和and
后来在 Perl 5 中添加,用于需要较低优先级的特定情况。例如,在 Perl 中,这里我们希望
||
具有较低的优先级,以便我们可以编写:并确保
||
不会吞噬部分内容的行动。 Perl 5 引入了or
,这是||
的新版本,优先级较低,正是为了这个目的。在 Ruby 中,您可以使用
或
但不能使用||
的示例:如果您使用
||
,则会出现语法错误。My guess is that's a direct carry-over from Perl. The operators
or
andand
were added later in Perl 5 for specific situations were lower precedence was desired.For example, in Perl, here we wish that
||
had lower precedence, so that we could write:and be sure that the
||
was not going to gobble up part of the action. Perl 5 introducedor
, a new version of||
that has low precedence, for exactly this purpose.An example in Ruby where you could use
or
but not||
:If you used
||
, it would be a syntax error.区别在于优先级。
||
、&&
的优先级高于=
,但and
、or有较低的。因此,虽然您可以这样做:但
您必须这样做:
才能获得相同的效果。如果这样做:
表达式的结果仍为 0,但值将为 nil。
The difference is precedence.
||
,&&
have higher precedence than=
, butand
,or
have lower. So while you can do:You would have to do:
to get same effect. If you do:
The result of expression would still be 0, but a value would be nil.
它们的优先级非常低,因此操作数不必用括号括起来,有时
&&
和||
就是这种情况。They have very low precedence so that the operands don't have to be wrapped in parentheses, as is sometimes the case with
&&
and||
.能够控制运算符的优先级有时很有用,特别是当您关心可读性时——条件语句中的额外括号有时会掩盖实际逻辑。
不过,坦率地说,我认为 Ruby 拥有布尔运算符优先级的原因主要源于这样一个事实:Matz 在编写 Ruby 之前是一名 Perl 程序员,并借用了该语言的大部分核心语法和运算符。
Being able to control the precedence of your operators is sometimes useful, especially if you are concerned with readability -- extra parenthesis in conditional statements can sometimes obscure the actual logic.
To be frank, though, I think the reason Ruby has the boolean operator precedence levels it does stems mostly from the fact that Matz was a Perl programmer before he ever wrote Ruby, and borrowed much of the core syntax and operators from that language.
我相信这个想法是专门让它们位于赋值运算符下方,这样您就可以使用赋值但不带括号来编写逻辑测试。
I believe the idea is specifically to get them below the assignment operators, so you can write logic tests with assignments but without parens.