What is a variable?

A variable is a name that Ruby associates with a particular object. For example:

city = "Toronto"  

Here Ruby associates the string “Toronto” with the variable city.

Think of it as Ruby making two tables. One with objects and another with names for them. Then think of Ruby drawing an arrow from city to "Toronto".

Whenever Ruby encounters city, it will follow the arrow and arrive at the string "Toronto".

Warning: Variable names must begin with a lowercase letter.

Working with variables

You can manipulate variables in exactly the same way that you would manipulate the objects that they represent.

shell> irb --simple-prompt
>> var1 = 7
=> 7
>> var2 = 4
=> 4
>> var3 = var1 + var2
=> 11
>> var4 = "hello"
=> "hello"
>> var4 = var4 * var2
=> "hellohellohellohello"

The good thing about variables is that you can keep track of information more easily. Suppose that you were given these instructions:

  1. Add 2, 4 , 6 and 8 together.
  2. Take that result, and divide it by 5
  3. Take the product of 2, 3 and 4.
  4. Take your answer from line 2 and subtract it from what you got in line 3.

Sure, you could write out a long expression to do this. It is much easier to write:

>> num1 = 2 + 4 + 6 + 8
=> 20
>> num1 = num1 / 5
=> 4
>> num2 = 2 * 3 * 4
=> 24
>> num2 = num2 - num1
=> 20

Shortcuts

In the example above, you saw the expressions:

num1 = num1 / 5
num2 = num2 - num1

These kinds of expressions are very common, so Ruby offers you some shortcuts:

Example Shortcut Meaning
var = var + 2 var += 2 Add 2 to var
var = var - 3 var -= 3 Subtract 3 from var
var = var * 6 var *= 6 Multiply var by 6
var = var / 2 var /= 2 Divide var by 2
var = var** 3 var **=3 Cube var
var = var % 4 var %= 4 var modulo 4

So the above example could be written as

>> num1 = 2 + 4 + 6 + 8
=> 20
>> num1 /= 5
=> 4
>> num2 = 2 * 3 * 4
=> 24
>> num2 -= num1
=> 20

Constants vs. variables

Constants are like variables, except that you are tellig Ruby that their value is supposed to remain fixed. If you try to change the value of a constant, Ruby will give you a warning.

You define constants just like variables, except that the first letter is uppercase. Although not required, it is common practice to make all the letters uppercase.

>> CITY = "Toronto"
=> "Toronto"
>> CITY = "Paris"
(irb):2: warning: already initialized constant CITY
=> "Paris"

Note: Though CITY is a “constant”, its value still changed. Being a constant only means that Ruby will warn you if you change its value.

EXERCISES

A Secret Note