Reusing variable names

It is also important to keep in mind that a name is unique, in the sense that the same name can only be assigned to one value (object) at a time.

In other words, if you assign different values to the same variable, then assignments that happen later will simply overwrite previous ones. Like so:

number = 4
number = number * 3
puts number + 2

This, again, would output 14.

Variable names can be re-used, and re-assigned.

The first line assigns the name number to the number 4. The second line re-assigns it to another object.

Getting back to our post-its metaphor … this would stick a post-it with the name number on one thing, and then later take it off of it, and stick it on something else.

Let’s look at it under the microscope:

Of course, you would probably never actually write this exact code in practice since you can simply do all this in just one line instead: puts 4 * 3 + 2.

However, sometimes you’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 sometimes is useful to break up long lines, and make code more readable.

Using variable names can be useful to break up long lines and make code more expressive and readable.

Also, Ruby 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. You will learn about another type of variables later when we talk about classes and objects.

On formatting: Note that there are spaces around the assignment operator `=` as well as the arithmetical operators `+` and `*`.