Variables
Prerequisites: Printing output
A variable is a name that refers to a value, so you can use or change that value later.
Real-world analogy: a variable is like a sticky label. You write a name on the label and stick it on a value. You can later peel the label off and stick it on a different value.
Syntax
name = "Ada"
There's no keyword (like let or var) and no type. Assigning a value
creates the variable.
Example
city = "Lagos"
age = 25
puts city
puts age
age = 26
puts age
age = age + 1
puts age
Expected output
Lagos
25
26
27
age = age + 1 reads the current value (26), adds one, and makes
age refer to the result. The shorter form age += 1 does the same.
Naming rules
- Use snake_case: lowercase words joined by underscores, like
first_nameortotal_price. - Names can contain letters, digits, and underscores, but can't start with a digit.
- Choose descriptive names:
total_priceexplains itself;tpdoesn't.
Constants
A name that starts with a capital letter is a constant — a value
meant to stay the same. By convention, constants are written in
SCREAMING_SNAKE_CASE:
MAX_PLAYERS = 4
Ruby lets you reassign a constant but prints a warning
(warning: already initialized constant MAX_PLAYERS) — treat that
warning as a bug.
Common mistakes
- Using a variable before assigning it:
undefined local variable or method 'score' for main (NameError). - Mixing up
Ageandage— the capitalized one is a constant, not the same variable.
Practice
Create a variable apples set to 5. Add 3 to it using +=, then
print I have 8 apples.
Hint: you can join text and a number with interpolation —
"I have #{apples} apples". The Strings lesson explains how it works.
Show solution
apples = 5
apples += 3
puts "I have #{apples} apples"