Thuta Learning
Ruby
BasicProgrammingBeginner

Variables & Constants

RubyLesson 525 min

What you'll walk away with

  • Explain a variable as a name that points at an object, and why age = "thirty" is legal
  • Name local variables in snake_case and constants in capitals
  • Show that b = a shares an object instead of copying it, and make a separate copy with dup
  • Use ||=, += and parallel assignment, and explain why a NameError appears inside a method

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.

copy_bug.rb
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.

Mental model: names pointing at objects
  1. A name is a label on an object
  2. = moves the label to another object
  3. b = a gives the SAME object a 2nd label
  4. << changes the object both labels share

Variables hold references, so use dup when you need a separate object.

General pattern: assignment

ruby
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 copy

Assigning 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.

variables.rb
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

  1. Assignment creates a variablefirst_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.

  2. A constantPI = 3.14159

    The 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.

  3. Names have no typeage = "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.

  4. A second labelnickname = greeting # a second name for the SAME object

    This 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.

  5. Mutation through one labelnickname << "!"

    << 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.

  6. 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.

You should see
Aung
30
true
3.14159
String
hi!
true

Constants, 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).

constants.rb
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_SIZES

In 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).

scope.rb
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.

shortcuts.rb
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
# 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
profile.rb
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

After a = "x", b = a and b << "y", what does puts a print?

Quick quiz 2 / 3

Which of these only prints a warning and keeps running?

Quick quiz 3 / 3

rate = 0.2 is set at the top of the file, and def tax(amount) uses amount * rate. What happens with puts tax(100)?

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

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Variables & Constants | Thuta Learning