Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding precedence of assignment and logical operator in 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

which is resolved as

1 + (2 * 3) + 4

it should be equal to:

x = (1 && y) = 2

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

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

Why?


EDIT [08.01.2016]

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

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

(1 && y) = 2

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?

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

like image 506
Michael Avatar asked Jan 07 '16 16:01

Michael


People also ask

What is the precedence of assignment operator?

Operators are listed in descending order of precedence. If several operators appear on the same line or in a group, they have equal precedence. All simple and compound-assignment operators have equal precedence.

What is an assignment operator in Ruby?

Ruby Assignment Operators Add AND assignment operator, adds right operand to the left operand and assign the result to left operand. c += a is equivalent to c = c + a. -= Subtract AND assignment operator, subtracts right operand from the left operand and assign the result to left operand.

What does === mean in Ruby?

In Ruby, the === operator is used to test equality within a when clause of a case statement. In other languages, the above is true.

Which operator has highest precedence in */ ()?

In Java, parentheses() and Array subscript[] have the highest precedence in Java. For example, Addition and Subtraction have higher precedence than the Left shift and Right shift operators.


1 Answers

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

x = (1 && y) = 2

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.

like image 87
sawa Avatar answered Oct 18 '22 11:10

sawa