理解 Ruby 中赋值和逻辑运算符的优先级 [英] Understanding precedence of assignment and logical operator in Ruby

查看:29
本文介绍了理解 Ruby 中赋值和逻辑运算符的优先级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解以下示例中 Ruby 运算符的优先级:

I can't understand precedence of Ruby operators in a following example:

x = 1 && y = 2

由于&&的优先级高于=,我的理解是类似于+*> 运营商:

Since && has higher precedence than =, my understanding is that similarly to + and * operators:

1 + 2 * 3 + 4

被解析为

1 + (2 * 3) + 4

它应该等于:

x = (1 && y) = 2

然而,所有 Ruby 源代码(包括内部语法解析器 Ripper)都将其解析为

However, all Ruby sources (including internal syntax parser Ripper) parse this as

x = (1 && (y = 2))

为什么?

编辑 [08.01.2016]

让我们关注一个子表达式:1 &&y = 2

Let's focus on a subexpression: 1 && y = 2

根据优先级规则,我们应该尝试将其解析为:

According to precedence rules, we should try to parse it as:

(1 && y) = 2

这没有意义,因为 = 需要特定的 LHS(变量、常量、[] 数组项等).但是既然 (1 && y) 是一个正确的表达式,那么解析器应该如何处理呢?

which doesn't make sense because = requires a specific LHS (variable, constant, [] array item etc). But since (1 && y) is a correct expression, how should the parser deal with it?

我试过咨询 Ruby 的 parse.y,但它太像意大利面条了,我无法理解具体的赋值规则.

I've tried consulting with Ruby's parse.y, but it's so spaghetti-like that I can't understand specific rules for assignment.

推荐答案

简单.Ruby 仅以有意义的方式解释它.= 是赋值.在您的期望中:

Simple. Ruby only interprets it in a way that makes sense. = is assignment. In your expectation:

x = (1 && y) = 2

1 && 分配一些东西是没有意义的y.您只能为变量或常量赋值.

it does not make sense to assign something to 1 && y. You can only assign something to a variable or a constant.

请注意,优先规则的目的是消除歧义表达的歧义.如果一种解释方法没有意义,那么就不需要消歧,因此优先规则将无效.

And note that the purpose of the precedence rule is to disambiguate an otherwise ambiguous expression. If one way to interpret it does not make sense, then there is no need for disambiguation, and hence the precedence rule would not be in effect.

这篇关于理解 Ruby 中赋值和逻辑运算符的优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆