Variables and Constants
The Bean Cart script needs to remember things: how many cups were sold today, and the price of a latte. One of those changes every hour; the other should change only when you print a new menu. Ruby lets you say which is which just by how you spell the name.
The rule
Lowercase names vary; a capital first letter declares a constant.
A variable is a name that points to an object. You create one simply by assigning to it. No keyword, no type:
cups_sold = 0
cups_sold = cups_sold + 1 # now 1
cart_name = "Bean Cart"Because Ruby is dynamically typed, the same name can later point to an object of a different type. That is allowed, though rarely a good idea.
A name that starts with a capital letter is a constant:
LATTE_PRICE = 4.50
MENU = { latte: 4.50, mocha: 5.00, tea: 2.50 }Ruby does not truly lock a constant. If you reassign one, the program keeps running, but Ruby prints a warning:
LATTE_PRICE = 4.75
# warning: already initialized constant LATTE_PRICETreat that warning as a bug report. Also note that a constant fixes which object the name points to, not what is inside the object. MENU[:tea] = 3.00 changes the hash without any warning. Call .freeze on it (MENU = { ... }.freeze) if you want Ruby to refuse such changes.
Ruby also marks a variable's reach with its first character. You will meet these properly later, but recognise them now:
| Prefix | Example | Meaning |
|---|---|---|
none (lowercase or _) |
cups_sold |
local variable |
@ |
@cups_sold |
instance variable, belongs to one object |
@@ |
@@carts_opened |
class variable, shared by a class |
$ |
$debug_mode |
global variable, visible everywhere (avoid) |
| Capital letter | LATTE_PRICE |
constant |
The shortcut
Look only at the first character of the name. Capital means constant. @, @@ or $ tell you its reach. A lowercase letter or underscore means a plain local variable.
TAX_RATE = 0.05First character
Tis a capital, so this is a constant. Reassigning it would trigger a warning.
That last step is the trap. People think constants must be ALL CAPS. The rule only needs the first letter to be a capital; all caps is simply the convention for values.
Drills
Answer fast — trust the rule.
What kind of name is cups_sold?
What happens when you run LATTE_PRICE = 4.50 and later LATTE_PRICE = 4.75?
Which of these names is a constant?
MENU = { tea: 2.50 } then MENU[:tea] = 3.00. What happens?
Remember
- Lowercase names vary; a capital first letter declares a constant.
- Read the first character: capital,
@,@@,$, or plain lowercase. - Trap: constants can be reassigned with only a warning, and their contents can change unless frozen.
