Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 134 ยท Control Flow

Immutability and freeze

Learn Ruby immutability - freeze, frozen?, FrozenError, frozen string literals, dup vs clone, constants, deep freezing and Ractor.make_shareable, with examples.

Most Ruby objects can change after you create them: strings grow, arrays get new elements, hashes gain keys. That flexibility is convenient, and it is also the source of a famous class of bugs, where one part of a program changes an object that another part still relies on. Ruby's answer is freeze: a one-way switch that turns an object read-only. Once frozen, any attempt to modify it raises FrozenError.

This lesson explains what freezing does and does not do, how strings, symbols and numbers differ, what Ruby 4.0 does with string literals, how dup and clone treat frozen objects, how to freeze constants and nested data properly, and where Ractor.make_shareable fits in.

freeze and frozen?

Ruby Freezing an array and a string

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.

Freezing blocks changes to the object itself. Everything that only reads or builds a new object still works. Note there is no unfreeze; to get a changeable version you make a copy (see below).

Now try to break the rule:

Ruby FrozenError (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 first attempt is rescued and prints rescued: can't modify frozen Array: ["Ada", "Grace"]. The second is not, so the program ends with main.rb:9:in '<main>': can't modify frozen Array: ["Ada", "Grace"] (FrozenError). The message names the class and shows the value, which makes the offending object easy to identify. FrozenError is a subclass of RuntimeError, and it has a receiver method that returns the frozen object.

What is already frozen

Some values are frozen from birth because they could never meaningfully change:

Ruby Objects that are frozen by themselves

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.

Integers, floats, symbols, nil, true, false, ranges and rationals are all immutable, so 42.frozen? is true and you cannot call a "change this number" method on them. Strings, arrays and hashes are mutable unless you freeze them. The line "text".frozen? deserves its own section.

String literals and Ruby 4.0

In older Ruby versions, every evaluation of "text" created a new mutable string. Newer versions are moving toward making literals frozen by default. Ruby 3.4 introduced a transitional state, and Ruby 4.0 keeps it: a plain literal is not yet frozen ("lit".frozen? is false), and mutating it works. Ruby calls such a string chilled.

Ruby Mutating a plain string literal

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 string is modified and nothing is printed, because the warning about chilled strings is a deprecation warning, and those are off by default. Turn them on (with ruby -w, -W:deprecated, or in code as below) and Ruby tells you where the literal was created:

Ruby Switching on the deprecation 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.

The output is hello world, and on standard error Ruby prints main.rb:4: warning: literal string will be frozen in the future (run with --debug-frozen-string-literal for more information). The line number is the line of the literal (line 4, where "hello" is written), not of the << on line 5. So today your code works, but a future release will raise FrozenError there. Write code that does not rely on mutating literals.

You have three tools to be explicit:

  • the magic comment # frozen_string_literal: true at the top of a file freezes every plain literal in it. It is the convention in nearly all modern Ruby code, and it also saves memory because identical literals can be shared;
  • .freeze on an individual literal;
  • String.new("text") or +"text" (unary plus) or "text".dup to get a fresh, mutable string.
Ruby The frozen_string_literal comment

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.

With the comment, title.frozen? is true and mutation raises can't modify frozen String: "report". Interpolated strings ("... #{x}") are built at run time and stay mutable. To build text piece by piece, start from +"" or String.new, or use arrays and join.

Add # frozen_string_literal: true to every file you write. It documents that you do not mutate literals, it catches accidental mutation early, and it avoids the warning above.

Freezing is shallow

freeze freezes the object you call it on, not the objects it contains.

Ruby The elements of a frozen array are still mutable

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 array rejects new elements, but the strings it holds can still change. Likewise, the hash refuses new keys while its inner array can grow. A "constant" holding a mutable collection is not constant at all.

To freeze a whole structure, do it recursively. A small helper does the job:

Ruby A deep_freeze helper

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 helper walks hashes and arrays and then freezes each container. Custom objects need their own handling (freeze their instance variables), which is why many teams prefer small immutable value types such as Data (Struct and Data). A Data instance is frozen automatically.

Freezing your own objects

Instance variables of a frozen object cannot be reassigned. A common pattern is to freeze in initialize so that the object is a value:

Ruby An immutable value 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.

A method such as + never changes the receiver; it returns a new Money. Code that holds a Money can share it freely, even across threads, because nothing can alter it. The sub call only shortens the error text, which contains an object address that differs between runs.

dup versus clone

Both create a shallow copy. They differ in what they keep:

Method Copy is frozen? Keeps singleton methods?
dup no, always unfrozen no
clone yes, if the original was yes
clone(freeze: false) no yes
Ruby dup, clone and frozen objects

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.

To get a changeable version of a frozen object, use dup. To keep it frozen, use clone. Both are shallow, so a frozen hash's dup still shares the same inner arrays. See Copying Objects for deep copies.

Constants are not immutable

A constant (MAX = 10, written in capitals) is only a name that you should not reassign. Reassigning prints a warning, but the object behind the name may still change unless it is frozen.

Ruby Constants and freeze

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 usual idiom for list or hash constants is .freeze, optionally with Ractor.make_shareable for deep freezing. With the magic comment, the strings inside %w[...] are already frozen, so SIZES is completely immutable.

Ractor.make_shareable

Ractor is Ruby's actor-style parallelism feature (see Ractors). Objects that cross between ractors must be shareable, meaning deeply frozen. Ractor.make_shareable does what our deep_freeze helper does, for all objects, including custom ones, and it is the standard way to deep freeze a configuration structure:

Ruby Deep freezing with Ractor.make_shareable

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.

Ractor.make_shareable freezes the object and everything reachable from it, and returns it; Ractor.shareable? tells you whether an object is already safe to share. You do not have to use ractors to benefit from the idea: a deeply frozen configuration object is a good idea in any program.

When to freeze

Freeze when:

  • you define constants (lists, lookup tables, default option hashes);
  • an object represents a value (money, coordinates, ranges) and equality by content makes sense;
  • you hand an internal collection to the outside and do not want callers to modify it; return list.dup or list.freeze from the reader method;
  • the object is shared between threads or ractors.

Do not bother freezing short-lived local objects that you build and mutate in a method. For building a large string or array, mutation is exactly what you want, and it is faster than creating many copies.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does freeze do to an array of strings?

    freeze is shallow. Elements are separate objects that must be frozen separately, for example with a recursive helper or Ractor.make_shareable.
  2. 2. Which class of error is raised when you modify a frozen object?

    FrozenError, a subclass of RuntimeError, is raised with a message such as can't modify frozen String.
  3. 3. Given s = "x".freeze, which statement returns an unfrozen copy?

    dup returns an unfrozen shallow copy. clone keeps the frozen state unless you pass freeze: false.
  4. 4. What does the comment # frozen_string_literal: true do?

    The comment applies to the file's plain literals. Strings built at run time, such as with interpolation, remain mutable.
  5. 5. Why is ITEMS = ["a", "b"] not truly constant?

    A constant only protects the name (and only by warning). Add .freeze to protect the object.

Summary

  • freeze makes an object read-only; modifying it raises FrozenError. There is no unfreeze: use dup for a mutable copy.
  • Numbers, symbols, nil, true, false and ranges are always frozen; strings, arrays and hashes are not.
  • Plain string literals are not frozen yet in Ruby 4.0, but mutating one warns. Use # frozen_string_literal: true.
  • freeze is shallow; freeze nested data recursively or use Ractor.make_shareable.
  • dup gives an unfrozen copy, clone preserves frozen state.
  • Freeze constants and value objects; keep mutation for local, short-lived building.

Next: Methods