Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 134 ยท Getting Started

Variables and Constants

Learn how Ruby variables really work - references, naming rules, local scope, constants, global and instance variables, multiple assignment and freezing.

A variable is a name that refers to a value. In Ruby you create one simply by assigning to it: age = 30. There is no var, no let and no type. That simplicity hides one idea you must understand early, because it explains many "surprises" later: a Ruby variable does not contain a value, it points to an object. Two variables can point to the very same object, and changing the object through one name shows up through the other.

This lesson covers the five kinds of names in Ruby (local variables, constants, instance variables, class variables and globals), how they are recognized by their first characters, how scope works, multiple assignment, and how freeze protects an object from change.

Creating and reassigning variables

Ruby Assignment and reassignment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The same name can refer to a string now and a number later, because the variable has no type; the object has one. Assignment with = is also an expression whose value is the assigned value, so a = b = 0 sets both to zero.

Naming rules and conventions

  • A local variable starts with a lowercase letter or an underscore: total, _unused, first_name.
  • Use snake_case: words in lowercase separated by underscores. firstName works but is not Ruby style.
  • Names can contain letters, digits and underscores, but cannot start with a digit. Non-ASCII letters are allowed, though most projects avoid them.
  • Reserved words such as class, end, if and def cannot be variable names.
  • A lone underscore (_) or a name starting with _ signals "I do not use this value".

Variables are references

Look at what happens when one variable is assigned to another.

Ruby Two names, one object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first part changes a "by accident", because << appends to the existing string object and both names point to it. Numbers behave differently: m += 1 means m = m + 1, which makes a new number and points m at it, leaving n alone. Integers cannot be changed in place at all. The difference is mutation (changing an object) versus rebinding (pointing a name at another object). Every Ruby programmer needs this distinction, and the same idea comes back in Strings, Immutability and freeze and Copying Objects.

equal? asks "are these the same object?", == asks "do they have equal contents?" The difference is detailed in Equality and Identity.

Local scope

A local variable exists only in the scope where it was assigned: the top level of the file, the inside of a method, or the inside of a class body. Ruby deliberately gives each def a fresh scope; it cannot see the local variables around it.

Ruby Methods cannot see outer locals (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The error is main.rb:4:in 'Object#show': undefined local variable or method 'count' for main (NameError). Inside show, count was never assigned, so Ruby looks for a method called count and fails. The fix is to pass the value in as an argument, which is also better design:

Ruby Pass values in with arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Blocks (the code between do ... end or { ... }) are different: they can see the variables around them, which is what makes them closures. Blocks and Closures and Binding cover that. Remember the rule: def, class and module start a new scope; blocks do not.

A subtle point: Ruby decides at parse time

Ruby notices an assignment when it compiles the file, so a variable exists from the moment its first assignment appears, even if that line never runs.

Ruby Variables that exist but were never assigned

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

defined? is a handy keyword that reports what a name refers to, or nil when it is nothing. It also explains why a typo in a variable name usually gives a NameError, but an unlucky if can silently give nil. Reading nil where you expected a value is the root of many Ruby bugs.

Constants

A name that starts with an uppercase letter is a constant. By convention constants hold values that should not change, and are written in SCREAMING_SNAKE_CASE. Class and module names are constants too (String, Math), written in CamelCase.

Ruby Constants and the reassignment warning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ruby does not forbid reassigning a constant; it prints warning: already initialized constant MAX_ATTEMPTS (plus previous definition of MAX_ATTEMPTS was here) on stderr and carries on. Treat that warning as a bug. Constants cannot be assigned inside a method at all:

Ruby Constants inside a method (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

This is a SyntaxError with the message dynamic constant assignment, because a method can run many times and a constant is meant to be assigned once. Define constants at the top level or in a class body, and use them from methods:

Ruby Using a constant from a method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Constants are looked up through the surrounding classes and modules, and you reach one from outside with ::.

Constants are not frozen

A constant always points at the same object, but the object itself can still be changed unless you freeze it.

Ruby freeze makes an object read-only

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

freeze is shallow: the array is locked, but the three strings inside it are not. Because of this, a robust constant often uses .map(&:freeze) or the frozen_string_literal comment. Numbers, symbols, nil, true and false are always frozen. The failure message of a frozen modification is can't modify frozen Array: ["S", "M", "L"] (FrozenError). Immutability and freeze goes much deeper.

Instance, class and global variables

Ruby marks the kind of variable with its first characters (the sigil). You will use some of these constantly and some almost never.

Name starts with Kind Where it lives
lowercase or _ local variable the current method, block or file
uppercase constant the class or module that defines it
@ instance variable one object (its state)
@@ class variable shared by a class and its subclasses (avoid)
$ global variable the whole program (avoid)

Instance variables hold an object's state and are the heart of object-oriented Ruby. A variable that was never assigned reads as nil, with no error.

Ruby Instance variables belong to an object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Each Counter has its own @count, invisible from outside except through methods. The last line even works at the top level, where self is the main object. See Classes and Objects.

Class variables (@@total) are shared by a class and all subclasses; they cause confusing bugs and are almost always replaced by "class instance variables", explained in Instance and Class Methods.

Global variables ($name) can be read and changed from anywhere, which makes programs hard to reason about. Ruby has a few useful built-in ones, such as $stdout, $stderr, $0 (the script name) and $PROGRAM_NAME. Prefer passing values around over inventing your own globals.

Ruby Why globals are risky

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Multiple assignment

Ruby can assign several variables at once. This is idiomatic and used constantly.

Ruby Multiple assignment, swapping and splat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The right side is evaluated completely before any assignment happens, which is why the swap works. A * collects the remaining values into an array. Ruby's rule is forgiving: missing values become nil and extra values are ignored.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. After a = "hi"; b = a; b << " there", what is a?

    Assignment copies the reference, not the string. << mutates the one shared object, so both names show the change. Use dup for an independent copy.
  2. 2. Why does def show; puts count; end fail when count is a local variable defined outside the method?

    Methods have their own local scope. The name count is treated as a method call and the result is a NameError. Pass the value as an argument instead.
  3. 3. What happens when you assign to an existing constant, as in MAX = 1 followed by MAX = 2?

    Constants are not enforced as read-only. Ruby warns on stderr and rebinds the name; treat that warning as a bug.
  4. 4. What does freeze do to LIST = %w[a b].freeze?

    freeze is shallow. The array rejects changes (FrozenError), while the element strings can still be modified unless you freeze them too.
  5. 5. What is the value of @name in a fresh object where it was never assigned?

    Unassigned instance variables read as nil. That convenience hides typos in names, so test and use attr_reader carefully.

Summary

  • A variable is a name pointing to an object; assignment copies the reference, and << mutates the shared object while += rebinds the name.
  • Local variables are lowercase snake_case; methods, classes and modules start new scopes, blocks do not.
  • Ruby creates a local variable at parse time, so an unassigned one reads as nil; defined? tells what a name is.
  • Constants start uppercase; reassigning only warns, and assigning inside a method is a SyntaxError.
  • freeze is shallow; numbers, symbols and nil are always frozen.
  • @name is instance state, @@name and $name are shared and best avoided.
  • Multiple assignment, swapping and * splats make destructuring short and clear.

Next: Basic Types