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

查看:119
本文介绍了了解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天全站免登陆