What are Variables?
Learn about variables and variable assignments.
We'll cover the following
Naming things
To refer to the objects our program deals with, we want to assign names to them. Every practical programming language has a feature to do this, called variables. In Ruby, there are different types of variables that we’ll explore soon.
Variable assignment
In Ruby, we can give a name to something (an object) by using the so-called assignment operator, =
, like so:
number = 1
This associates the name number
with the object, which is the number 1
. From now on, we can refer to this object by using the name number
.
Note: A name on the left side of the = operator is assigned to the object on the right side.
For example, the following code outputs the number 1
:
number = 1puts number
Variables aren’t things
Note that a variable isn’t a thing, or an object by itself. Instead, it’s just a name for an actual object. In our example, the number 1
is an object, while number
is a name we’ve assigned it. Whenever we use a variable name that’s been defined before, we’re actually referring to the object assigned to it. So, line 2 of the code above prints the number 1
.
a = 1puts alarge_number = 1puts large_numberapples = 1puts apples
Note, however, that it makes sense to try and pick names that reveal our intentions. We’ll talk more about this by the end of the course. In short, the first example using a as a name isn’t ideal because it’s not a meaningful name. The second and third examples are simply misleading because they don’t reflect the nature of the object they represent (number 1
) at all.
Think of this like a Post-it note with the name number
written on it, which is stuck on the actual thing, which is an object (in this case, a number).
Imagine trying to learn some Spanish, and so you stick Post-its onto things in your apartment: the word ”nevara” on the refrigerator, ”cama” on the bed, and “puerta del baño” on the bathroom door.
Whenever you use one of these terms in a sentence, as in “abrir la nevera” (open the refrigerator), you’re obviously referring to the physical refrigerator and not the Post-it note.