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.
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.
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.
In Ruby, the === operator is used to test equality within a when clause of a case statement. In other languages, the above is true.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With