Maksym Bykovskyy
Maksym Bykovskyy

Reputation: 832

Operator precedence of assignment and conditional operators

I'm reading a book called "The Ruby Programming Language" for Ruby 1.8 and 1.9. The book says that if-operator has a lower precedence than an assignment-operator. If this is true then I don't understand how this expressions works:

x = 5 if false

If assignment-operator has a higher precedence then it should be executed before an if-operator. So, 5 should be assigned to x before if false is executed.

Am I misunderstanding precedence?

Upvotes: 1

Views: 611

Answers (2)

Nikita Rybak
Nikita Rybak

Reputation: 68046

Higher precedence of assignment means that your expression evaluates to (x = 5) if false, and not to x = (5 if false). Note, that later is a perfectly valid expression too.

Whether each particular clause is executed is determined by language rules. E.g., in a ternary operator a ? b : c, only b or c will be executed, but not both.

edit
About the difference.

In x = (5 if false), assignment is processed first. But to complete it, we need left part of assignment, which is nil, because 5 if false evaluates to nil. So, the expression is equivalent of x = nil.

In (x = 5) if false, conditional operator is processed first. According to its rules, we first have to evaluate condition (false). Since it's false, there's nothing more to do and result of evaluation is nil.

Hope that's clear.

Upvotes: 1

Nakilon
Nakilon

Reputation: 35112

Because <expr> if <condition> is not a one expression. It is a special syntaxic sugar of Ruby. It works just like:

if <condition>
    <expr>
end

where, obviously, <expr> must be evaluated only after <condition> because <condition> can be false.

Upvotes: 0

Related Questions