Things on the Right Go First
Learn about how variable assignment works.
We'll cover the following
Final remarks
One last thing to note about assignments to variables is that things on the right side go first.
To assign the thing on the right side to the name on the left side, Ruby first needs to interpret what’s on the right. As we’ll see later, the same is true for many other expressions in Ruby.
Example
number = 2 + 3 * 4puts number
When Ruby looks at line 1, number = 2 + 3 * 4
, it notices that it uses the =
operator. Therefore, before it can assign number
to the object on the right, it first needs to know what that thing is.
How does Ruby do it
So, Ruby first looks at the 2 + 3 * 4
expression and evaluates it, producing the number 14
. It then refers to this object by the name number
(evaluates the =
operator).
Imagine that when Ruby starts evaluating the =
operator, the code temporarily looks like number = 14
because the calculation returns 14
.
Again, in line 2, Ruby passes the thing with number (14) to puts
, which outputs it to the screen.
Remember: Ruby evaluates the expression on the right first. The arithmetic expression itself is evaluated using the operator
. precedence rules Divisions and multiplications are evaluated before additions and subtractions