Explain it simply
Variables in plain words
A variable is a name you give to a value so you can use it again. In Ruby you create one just by writing name = value; there is nothing to declare and no type to state. A better picture than a box that holds a value is a sticky label attached to an object: the label can be moved to another object, and two labels can be stuck on the same object. Names are written in snake_case, like first_name, and a name that starts with a capital letter, like PI, is a constant meant to stay fixed.
Problem → Why → Solution
The problem: a copy that is not a copy
You store a customer's name, make a "copy" to edit, and later discover that the original changed too. In a language where a variable is a box holding a value, that cannot happen. In Ruby it can, because assignment does not copy the object; it gives the same object a second name. The bug is easy to miss: no error is raised, the output is simply different from what you expected, and the change may happen inside a method far from where you notice it.
Other common stumbles belong to the same family: a name such as 1name is a SyntaxError, a name starting with a capital letter silently becomes a constant, and a variable from the top of the file is invisible inside a method. This lesson explains all of them with one picture, the label on an object.
original = "hello"
copy = original
copy << " world"
puts original # prints "hello world", not "hello"Variables are labels
Ruby variables are labels attached to objects. Assigning one variable to another attaches a second label to the same object, so a change made through either label changes the object itself and both labels show it. Once you see that, it is clear when a copy is needed (dup) and when sharing is harmless.
Core concept: a variable is a name that points at an object
A variable is a name that points at an object. Writing age = 30 creates the name age if it does not exist yet and makes it point at the Integer 30; there is no var, let or type to declare first. Ruby variables carry no type at all, the objects do, which is why age = "thirty" is legal one line later and age.class then answers String.
Because a variable is a pointer and not a box, assigning one variable to another copies the pointer, not the object. After nickname = greeting both names point at the same string, so changing it through one name, for example with <<, shows up through the other. Methods that change an object in place are called mutating methods; methods that return a new object, such as upcase, leave the original alone. To get an independent copy, call dup.
Names follow rules. Local variables start with a lowercase letter or an underscore and use snake_case: first_name, total_price. A name cannot start with a digit (1name is a syntax error) or contain spaces or hyphens. A name that starts with a capital letter is a constant, meant to hold a value that should not change, such as PI or MAX_RETRIES. Ruby does not enforce this: reassigning a constant only prints a warning, and a constant that holds a changeable object such as a string or an array can still be changed unless you freeze it. Other prefixes mark other kinds of variable, @ for instance variables, @@ for class variables and $ for globals, which later lessons cover.
A local variable exists only where it was created. Variables made at the top of a file are not visible inside a def method, which gets its own fresh scope; pass values in through parameters. Also note that a variable assigned inside an if branch that never runs still exists, with the value nil, because Ruby creates the name when it parses the assignment.
- A name is a label on an object
- = moves the label to another object
- b = a gives the SAME object a 2nd label
- << changes the object both labels share
Variables hold references, so use dup when you need a separate object.
General pattern: assignment
local_name = value # snake_case, created by assignment
CONSTANT_NAME = value # a capital first letter makes a constant
other = local_name # a second name for the same object
other = local_name.dup # a separate copyAssigning to a lowercase name creates a local variable, and a capital first letter makes a constant. other = local_name attaches a second name to the same object, while other = local_name.dup creates a separate copy and points at that. No type appears anywhere.
Example: variables, a constant and two labels
The first half shows plain variables and a constant; the second half shows the label picture: a variable that changes type and two names for one string. Predict the final value of greeting before you run it.
first_name = "Aung" # local variable (snake_case)
age = 30
is_student = true
PI = 3.14159 # constant (capital first letter)
puts first_name
puts age
puts is_student
puts PI
age = "thirty" # the name now points at a String
puts age.class
greeting = "hi"
nickname = greeting # a second name for the SAME object
nickname << "!"
puts greeting
puts greeting.equal?(nickname)Code breakdown
- Assignment creates a variable
first_name = "Aung"This line creates the name first_name and points it at a String object. The name is in snake_case and no type is written anywhere.
- A constant
PI = 3.14159The capital first letter makes PI a constant. Writing PI = 3 later makes Ruby send an already initialized constant PI warning to stderr and carry on; it does not stop.
- Names have no type
age = "thirty"age used to point at the Integer 30 and now points at a String. That is allowed, and .class answers String, because the type belongs to the object and not to the name.
- A second label
nickname = greeting # a second name for the SAME objectThis line creates no new string; nickname points at the very object that greeting points at. That is why SAME is written in capitals in the comment.
- Mutation through one label
nickname << "!"<< changes the string in place by appending "!". Since there is only one object, looking at it through greeting also shows hi!. This works because the file has no # frozen_string_literal: true comment.
- Same object?
puts greeting.equal?(nickname)equal? asks whether the two names point at one object, not whether the values look alike. The answer is true. Had nickname been made with dup, it would be false.
Aung
30
true
3.14159
String
hi!
trueConstants, warnings and freezing
Reassigning a constant prints a warning instead of raising an error, and the value changes. More important, a constant protects only the name, not what is inside the object. An array stored in a constant can still be changed with <<. If you really want it unchanged, freeze the object. In the code below, %w[S M L] is an array of three strings (a later lesson covers arrays).
MAX_RETRIES = 3
MAX_RETRIES = 5 # warning on stderr, the value changes
puts MAX_RETRIES
SIZES = %w[S M L].freeze
puts SIZES.frozen?
OPEN_SIZES = %w[S M L]
OPEN_SIZES << "XL" # allowed: only the name is constant
p OPEN_SIZESIn Ruby 4.0.9 this code writes two warning lines to stderr (already initialized constant MAX_RETRIES and previous definition of MAX_RETRIES was here) and prints 5, true and ["S", "M", "L", "XL"].
Scope: where a variable can be seen
def starts a new scope. Local variables from outside are not visible inside it, so a method that tries to use an outer rate raises NameError. The fix is to pass rate in as a parameter, which also makes the method's needs visible at the call site. The code below catches the error with rescue and prints its message (exceptions get their own lesson later).
rate = 0.2
def tax(amount)
amount * rate # rate does not exist in here
end
begin
puts tax(100)
rescue NameError => e
puts e.message
end
def tax_with(amount, rate)
amount * rate
end
puts tax_with(100, rate)In Ruby 4.0.9 the first output is undefined local variable or method 'rate' for main and the second is 20.0. Notice "local variable or method" in the message: Ruby looked for the name both as a variable and as a method.
Assignment shortcuts
A few Ruby forms shorten everyday assignments. count += 1 is shorthand for count = count + 1. nickname ||= "guest" assigns only when nickname is nil (or false), which makes it popular for default values. a, b = b, a swaps two variables without a temporary.
count = 0
count += 1
count += 1
puts count
nickname = nil
nickname ||= "guest"
nickname ||= "other"
puts nickname
a, b = 1, 2
a, b = b, a
puts "#{a} #{b}"This code prints 2, guest and 2 1. The second ||= does not store "other" because nickname already has a value.
In real projects
Variables and constants in real projects
Constants are how Ruby code names its configuration: MAX_RETRIES = 3, API_URL = "https://example.com", DEFAULT_PAGE_SIZE = 25. Keeping such values in one named constant instead of repeating them means a change happens in one place, and a frozen constant (SIZES = %w[S M L].freeze) stops code elsewhere from altering shared data by accident.
The aliasing behaviour is behind many real bugs. A method receives a hash or a string, changes it with a mutating method, and the caller's data changes as well. Experienced Ruby developers therefore prefer methods that return new objects (upcase over upcase!), call dup when they must change a copy, and put # frozen_string_literal: true at the top of files, so that an accidental in-place edit of a string literal raises a FrozenError instead of causing a silent bug. RuboCop's naming checks also flag names that break snake_case.
Common mistakes
Common beginner mistakes
1. Assuming b = a makes a copy
After b = a, running b << "x" changes a too, because there is only one object. Write b = a.dup instead. With # frozen_string_literal: true at the top of the file, << raises a FrozenError, which is useful because it exposes the bug early.
2. Starting a variable name with a capital letter
Total = 5 is a constant, not a variable. Writing Total = 6 later prints an already initialized constant Total warning. The program keeps running, but the name misstates your intent, so write total in lowercase.
3. Expecting an outer variable inside a method
If you write rate = 0.2 at the top of the file and use rate inside def tax(amount), you get undefined local variable or method 'rate'. Methods cannot see outward; pass rate in as a parameter. A typo such as totl produces the same message, so check the spelling of the name as well.
Best practices
Best practices
- Choose names that say what the value means: unit_price or remaining_lessons reads better than p or x1.
- When a constant holds an array or a hash, add .freeze so that the contents are protected, not only the name.
- Do not change a method's argument in place; return a new result, and if you must change something, copy it with dup first.
Mini challenge
Mini challenge: profile defaults
In one script, set a default name with ||=, swap two values with parallel assignment, take a backup with dup, and check a length limit stored in a constant.
- Use username = "aye" and nickname = nil, then make nickname the uppercase form of username with ||= and print it
- Swap first = "A" and second = "B" with parallel assignment and print the two together
- Back up title = "Intro" with dup, append " to Ruby" to title, and print both title and the backup
- Use a constant MAX_LENGTH = 10 and print whether title.length is within the limit as "Fits: ..."
# profile.rb
# TODO 1: give nickname a default with ||= (the uppercase form of username)
# TODO 2: swap two values with one parallel assignment and print them together
# TODO 3: back up title with dup, then change title with <<
# TODO 4: add the constant MAX_LENGTH and print "Fits: true" or "Fits: false"Expected: The program prints these five lines: AYE BA Intro to Ruby Intro Fits: false
Show hint
nickname ||= username.upcase stores username.upcase because nickname is nil. Swap with first, second = second, first. title << " to Ruby" changes title but not backup = title.dup, so dup must be called before the <<. "Intro to Ruby" has 13 characters, which is over the limit of 10.
Show solution
username = "aye"
nickname = nil
nickname ||= username.upcase
puts nickname
first = "A"
second = "B"
first, second = second, first
puts "#{first}#{second}"
title = "Intro"
backup = title.dup
title << " to Ruby"
puts title
puts backup
MAX_LENGTH = 10
puts "Fits: #{title.length <= MAX_LENGTH}"Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A variable is a name that points at an object; the type lives on the object, which is why age = "thirty" is allowed
- b = a shares the object instead of copying it, a mutating method such as << shows through both names, and dup makes a separate copy
- Local variables use snake_case, a capital first letter makes a constant, and reassigning a constant only warns
- def starts a new scope, so outer variables are invisible inside it; pass values in as parameters
Official Ruby Documentation — Ruby Documentation