Reusing Variable Names
Learn how variables can be useful.
We'll cover the following
It’s also important to keep in mind that a name is unique in the sense that the same name can only refer to one value (object) at a time.
If we successively assign different values to the same variable, the latest one will remain. The previous value of the variable is overwritten, like so:
number = 4number = number * 3puts number + 2
Line 1 assigns the number 4 to the name number
. Line 2 reassigns another object to it. Essentially, the same name is now referring to a different object.
In terms of our Post-its metaphor, this is like sticking a Post-it with the name number
on one thing and then later taking it off to stick it on something else.
Code briefing
Let’s take a closer look at this:
- In line 1, Ruby creates the number (object)
4
. It then refers to this object by the name number. - In line 2, Ruby looks at the contents of the right side and evaluates the expression
number * 3
. To do this, it creates the number (object)3
and multiplies it with the object that currently has the namenumber
, which is4
. This operation results in a new number (object),12
. - Ruby is now ready to stick
number
on the result,12
. The name number now refers to a different object, which is12
. - In line 3, Ruby looks at the expression
number + 2
on the right. It creates the2
object and adds it to the object that currently has thenumber
name. This results in a new number (object) of14
. - Finally, Ruby passes this
14
toputs
, which outputs it to the screen.
Code in practice
Of course, we’d probably never write this exact code in practice because we can simply obtain the same result in a single line: puts 4 * 3 + 2
.
Sometimes we’ll find or write code that assigns an initial value to a variable and then keeps working on it for a few more lines. This is occasionally useful for breaking up long lines and making the code more readable.
Ruby also has different kinds of variables.
The kind of variable that we’ve introduced so far is called a local variable, and it’s the one used most often. There are other kinds of variables, such as global, instance, and class variables. We’ll look into some of these later in the course.
Note: There are spaces around the assignment operator, =
, as well as the arithmetic operators, +
and *
.