“和”、“或”背后有什么智慧吗? Ruby 中的运算符?

发布于 2024-08-05 03:24:12 字数 121 浏览 9 评论 0原文

我想知道为什么 ruby​​ 的 andor 优先级低于 &&|| 和赋值运算符?有什么理由吗?

I wonder why ruby give and, or less precedence than &&, || , and assign operator? Is there any reason?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

小梨窩很甜 2024-08-12 03:24:12

我的猜测是这是 Perl 的直接继承。运算符 orand 后来在 Perl 5 中添加,用于需要较低优先级的特定情况。

例如,在 Perl 中,这里我们希望 || 具有较低的优先级,以便我们可以编写:

try to perform big long hairy complicated action     || die ;

并确保 || 不会吞噬部分内容的行动。 Perl 5 引入了 or,这是 || 的新版本,优先级较低,正是为了这个目的。

在 Ruby 中,您可以使用 但不能使用 || 的示例:

value = possibly_false or raise "foo"

如果您使用 ||,则会出现语法错误。

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.

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 ;

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.

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.

路还长,别太狂 2024-08-12 03:24:12

区别在于优先级。 ||&& 的优先级高于 =,但 andor有较低的。因此,虽然您可以这样做:但

a = nil || 0

您必须这样做:

a = (nil or 0)

才能获得相同的效果。如果这样做:

a = nil or 0

表达式的结果仍为 0,但值将为 nil。

The difference is precedence. ||, && have higher precedence than =, but and, or have lower. So while you can do:

a = nil || 0

You would have to do:

a = (nil or 0)

to get same effect. If you do:

a = nil or 0

The result of expression would still be 0, but a value would be nil.

來不及說愛妳 2024-08-12 03:24:12

它们的优先级非常低,因此操作数不必用括号括起来,有时 &&|| 就是这种情况。

They have very low precedence so that the operands don't have to be wrapped in parentheses, as is sometimes the case with && and ||.

他不在意 2024-08-12 03:24:12

能够控制运算符的优先级有时很有用,特别是当您关心可读性时——条件语句中的额外括号有时会掩盖实际逻辑。

不过,坦率地说,我认为 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.

最终幸福 2024-08-12 03:24:12

我相信这个想法是专门让它们位于赋值运算符下方,这样您就可以使用赋值但不带括号来编写逻辑测试。

I believe the idea is specifically to get them below the assignment operators, so you can write logic tests with assignments but without parens.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文