Values and references

suggest change

In Ruby every value is an object, and a variable doesn't contain an object. It holds a reference to one. Many questions about Ruby code come down to this: why changing one variable changes another, why a method changed its argument, or why Array.new(3, []) acts strangely.

This article covers:

All examples were run with Ruby 4.0.

Variables hold references

Assignment never copies an object. It makes the variable on the left refer to the same object as the expression on the right:

a = "hello"
b = a

puts a.object_id == b.object_id
puts a.equal?(b)

b << " world"
puts a
true
true
hello world

a and b are two names for one String. << modifies that string in place, so the change shows up through both names.

Every object has an object_id that stays the same for its whole lifetime. equal? returns true only when both sides are the same object. Ruby classes are not supposed to override it.

Mutating vs. rebinding

There are two different things you can do with a variable:

Only mutation is visible through other references. Here is the previous example with += instead of <<:

a = "hello"
b = a

b += " world"   # same as b = b + " world"
puts a
puts b
puts a.equal?(b)
hello
hello world
false

b + " world" builds a new string, and = points b at it. a still refers to the original string, which hasn't changed.

The object_id shows which operations keep the same object:

s = "abc"
before = s.object_id

s << "d"           # mutates
s.concat("e")      # mutates
s.replace("xyz")   # mutates: same object, new contents
p s, s.object_id == before

s = s + "!"        # new object
p s, s.object_id == before
"xyz"
true
"xyz!"
false

By convention, a method ending in ! is the "dangerous" version of a method without one. Usually the bang version modifies the receiver (upcase!, map!, sort!, compact!) and the plain version returns a new object. Some methods mutate without a ! too, such as <<, push, concat, replace, clear, delete, insert and []=. Check the documentation when you're not sure.

Immediate values

Small integers, floats, symbols, nil, true and false are immediate values. The reference itself encodes the value, so there is only ever one 42 and one :name:

p 42.equal?(42)
p (2**70).equal?(2**70)
p 1.5.equal?(1.5)
p :name.equal?(:name)
p "abc".equal?("abc")
p 42.frozen?, :a.frozen?, nil.frozen?, 1.5.frozen?
true
false
true
true
false
true
true
true
true

2**70 is too large for an immediate integer, so each evaluation creates a new Integer object. Every string literal also creates a new string (see below).

Numbers, symbols, nil, true and false are frozen and have no methods that change them. So in practice they act like values in other languages: you can share them freely and nobody can change them under you. Arithmetic always returns a new number and rebinds the variable:

x = 10
y = x
y += 1
p x, y

n = 5
n.succ   # returns 6, n is unchanged
p n
10
11
5

Passing arguments to methods

Ruby passes arguments the same way it assigns variables. The parameter becomes another reference to the caller's object. This is sometimes called pass by object reference or call by sharing. It is not pass by value (the object isn't copied) and it is not pass by reference in the C++ sense (the method can't rebind the caller's variable).

So a method can mutate an object it receives, but assigning to the parameter only changes the local variable:

def add_item(list)
  list << "new"
end

def replace_list(list)
  list = ["replaced"]
end

items = ["old"]
add_item(items)
p items

replace_list(items)
p items
["old", "new"]
["old", "new"]

The same applies to strings. The method decides whether your object gets changed:

def shout(s)
  s.upcase!
end

def shout_copy(s)
  s.upcase
end

name = "ann"
shout_copy(name)
p name
shout(name)
p name

def show_id(obj) = obj.object_id
arr = []
p show_id(arr) == arr.object_id
"ann"
"ANN"
true

Since integers can't be mutated, a method can't change a caller's number "in place". It has to return the new value, or update a container that the caller also holds:

def increment(n)
  n += 1
end

count = 0
increment(count)
p count

count = increment(count)
p count

def increment_all(counts, key)
  counts[key] += 1
end

counts = Hash.new(0)
increment_all(counts, :clicks)
increment_all(counts, :clicks)
p counts
0
1
{clicks: 2}

Default parameter values are evaluated on every call, so a default [] is a new array each time. This is different from Python:

def append(item, list = [])
  list << item
end

p append(1)
p append(2)     # a fresh [] each call, unlike Python
[1]
[2]

As a rule, methods should not mutate their arguments unless that's what they're for, and in that case a ! in the name or a clear name (add_to!, fill) should say so. Common pitfalls has more examples.

Equality vs. identity

Because two variables can refer to different objects with the same contents, Ruby has more than one comparison:

Method Question it answers
equal? Are these the same object?
== Do these have the same value? (classes define what that means)
eql? Same value and same type? Used for Hash keys, together with hash
a = "ruby"
b = "ruby"
c = a

p a == b        # same contents
p a.equal?(b)   # same object?
p a.equal?(c)

p 1 == 1.0
p 1.eql?(1.0)   # eql? also compares type
true
false
true
true
false

For your own classes, the == inherited from Object is identity, the same as equal?. Two objects with equal fields are not == unless you define it. Data and Struct define == based on their members:

class Point
  attr_reader :x, :y

  def initialize(x, y)
    @x, @y = x, y
  end
end

p Point.new(1, 2) == Point.new(1, 2)

Pt = Data.define(:x, :y)
p Pt.new(x: 1, y: 2) == Pt.new(x: 1, y: 2)
p Pt.new(x: 1, y: 2).equal?(Pt.new(x: 1, y: 2))
false
true
false

See Comparable and Overriding hash function for defining equality on your own classes.

String literals create new objects

Each time Ruby evaluates a string literal, it creates a new String. Two calls to a method that returns "item" give you two different objects, so mutating one doesn't affect the other:

def label = "item"

a = label
b = label
p a.equal?(b)
a << "!"
p a, b
p "x".frozen?
false
"item!"
"item"
false

The # frozen_string_literal: true magic comment changes this. Each literal then refers to a single frozen string, which saves allocations:

# frozen_string_literal: true

def label = "item"
p label.equal?(label)
p label.frozen?
begin
  label << "!"
rescue FrozenError => e
  puts e.message
end
s = +"item"   # unary plus returns an unfrozen copy
s << "!"
p s
true
true
can't modify frozen String: "item"
"item!"

Without the comment, literals in Ruby 3.4 and 4.0 are "chilled": they still work as mutable strings, but mutating one warns when deprecation warnings are enabled, because literals are planned to become frozen by default:

$ ruby -W:deprecated lit.rb
false
lit.rb:6: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information)
"item!"
"item"
false

Use +"..." or String.new when you need a string you're going to build up in place.

Shared objects in collections

A collection holds references, just like a variable does. Putting the same object into several slots shares it between them. This is the classic Array.new mistake:

grid = Array.new(3, [])
grid[0] << :x
p grid
p grid.map(&:object_id).uniq.size

grid = Array.new(3) { [] }
grid[0] << :x
p grid

a = b = []
b << 1
p a

row = [0] * 3
rows = [row] * 2
rows[0][0] = 9
p rows
[[:x], [:x], [:x]]
1
[[:x], [], []]
[1]
[[9, 0, 0], [9, 0, 0]]

Array.new(3, []) evaluates [] once and puts that one array in all three slots. The block form runs once per slot and creates a new array each time. a = b = [] and [row] * 2 share one object in the same way.

Hash.new(default) has the same problem. The default object is returned for every missing key, so mutating it changes the default and doesn't store anything in the hash:

groups = Hash.new([])
groups[:a] << 1
groups[:b] << 2
p groups          # nothing stored!
p groups[:zzz]    # the shared default was mutated

groups = Hash.new { |h, k| h[k] = [] }
groups[:a] << 1
groups[:b] << 2
p groups
{}
[1, 2]
{a: [1], b: [2]}

See Setting Default Values for more on hash defaults.

Mutable hash keys

A Hash stores keys by their hash value at the time of insertion. String keys are special-cased: the hash copies and freezes an unfrozen string key, so changing your original string can't break the hash. Other mutable keys are not copied, and mutating one makes the entry unreachable until you call rehash:

key = "name"
h = { key => "Ann" }
key << "!"
p h                         # Hash dup-and-froze the string key
p h.keys.first.frozen?

list = [1, 2]
h2 = { list => "pair" }
list << 3
p h2[[1, 2, 3]]             # nil: hash code changed
h2.rehash
p h2[[1, 2, 3]]
{"name" => "Ann"}
true
nil
"pair"

Use immutable objects (symbols, frozen strings, numbers, Data instances) as hash keys.

Block variables are references too

In each, the block parameter refers to each element in turn. Assigning to it only rebinds the block's local variable. Calling a mutating method changes the element itself:

words = ["a", "b"]
words.each { |w| w = w.upcase }   # rebinds the block variable only
p words

words.each { |w| w.upcase! }      # mutates each element
p words

nums = [1, 2]
nums.each { |n| n += 10 }         # integers can't be mutated
p nums
p nums.map { |n| n + 10 }
["a", "b"]
["A", "B"]
[1, 2]
[11, 12]

To transform a collection, use map (new array) or map! (replace elements in place) rather than assigning to the block variable.

Blocks and lambdas capture variables, not the values those variables had when the block was created. A later rebinding is visible inside the block, and the block can rebind outer variables:

total = 0
add = ->(n) { total += n }   # captures the variable, not its value
add.(5)
add.(7)
p total

msg = "hi"
greet = -> { msg }
msg = "bye"                  # rebinding is visible to the lambda
p greet.()

callbacks = []
3.times { |i| callbacks << -> { i } }   # each block call gets its own i
p callbacks.map(&:call)
12
"bye"
[0, 1, 2]

Block parameters like i are new variables on each call, so unlike var loops in older JavaScript, each lambda sees its own value.

Objects that leak their internals

An object that keeps a reference it was given, or returns a reference to its own state, shares that state with whoever holds the other reference:

class Playlist
  attr_reader :songs

  def initialize(songs)
    @songs = songs
  end
end

input = ["Intro"]
pl = Playlist.new(input)
input << "Outro"          # caller still holds the same array
pl.songs << "Bonus"       # reader hands out the internal array
p pl.songs
["Intro", "Outro", "Bonus"]

Both the caller and code using songs changed the playlist without going through any of its methods. When that matters, copy on the way in and hand out a copy (or a frozen copy) on the way out:

class Playlist
  def initialize(songs)
    @songs = songs.dup      # copy on the way in
  end

  def songs = @songs.dup.freeze   # copy on the way out

  def add(song)
    @songs << song
    self
  end
end

input = ["Intro"]
pl = Playlist.new(input)
input << "Outro"
begin
  pl.songs << "Bonus"
rescue FrozenError => e
  puts e.message
end
pl.add("Bonus")
p pl.songs
can't modify frozen Array: ["Intro"]
["Intro", "Bonus"]

Setters have the same issue. u.name = n stores a reference to the caller's string:

class User
  attr_accessor :name
end

u = User.new
n = "ann"
u.name = n
n.capitalize!
p u.name

u.name = n.dup
n << "!"
p u.name
"Ann"
"Ann"

Memoized values are another common source of this bug. The cached object is returned to every caller, so one caller's mutation is seen by all later ones:

def tags
  @tags ||= ["ruby"]
end

t = tags
t << "rails"
p tags     # the memoized array was mutated through t
["ruby", "rails"]

Freezing the cached value (@tags ||= ["ruby"].freeze) turns such mutations into an immediate FrozenError instead of a mystery.

Constants are references

A constant is a name that shouldn't be rebound. It says nothing about whether the object it refers to can change. Ruby warns when you reassign a constant, but not when you mutate the object it refers to:

COLORS = ["red", "green"]
COLORS << "blue"            # no warning: the constant still refers to the same array
p COLORS

LIMITS = { max: 10 }.freeze
begin
  LIMITS[:max] = 20
rescue FrozenError => e
  puts e.class
end

NAMES = ["ann", "bob"].freeze
NAMES.first << "!"          # freeze is shallow
p NAMES

NAMES2 = ["ann", "bob"].map(&:freeze).freeze
p NAMES2.all?(&:frozen?)
p Ractor.make_shareable([["deep"], { k: "v" }]).then { |o| [o.frozen?, o[0].frozen?, o[0][0].frozen?, o[1][:k].frozen?] }
["red", "green", "blue"]
FrozenError
["ann!", "bob"]
true
[true, true, true, true]

freeze only freezes the object it's called on, not the objects it refers to. Ractor.make_shareable freezes an object and everything reachable from it, which makes it a handy deep freeze. See Immutability for more.

Copies are shallow

dup and clone copy the object itself, but the copy refers to the same nested objects as the original:

original = [["a"], ["b"]]
shallow = original.dup

shallow << ["c"]            # the outer array is a new object
shallow[0] << "x"           # the inner arrays are shared
p original
p shallow
p original[0].equal?(shallow[0])

deep = Marshal.load(Marshal.dump(original))
deep[0] << "y"
p original
p deep
[["a", "x"], ["b"]]
[["a", "x"], ["b"], ["c"]]
true
[["a", "x"], ["b"]]
[["a", "x", "y"], ["b"]]

Marshal.load(Marshal.dump(obj)) makes a deep copy, but it fails for objects that can't be marshaled (procs, IO objects, singleton methods). Copying and cloning covers dup vs. clone, deep copies and initialize_copy in detail.

Guidelines

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents