Variables and Constants
Variables bind names to objects. Constants use names beginning with an uppercase letter and can warn on reassignment; a constant binding does not freeze the object it references.
Distinguish variable assignment from constant naming and object mutation.
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 |