TExcelTAD
Home › Ruby › Ruby Freezing & Immutability

Ruby Freezing & Immutability

In Ruby most objects — strings, arrays, hashes, your own objects — are mutable: their contents can change after creation. Sometimes you want the opposite: an object that can never change. Calling freeze makes an object immutable, and Ruby raises a FrozenError if anyone tries to modify it.

freeze and frozen?

ruby · try it yourself
colors = ["red", "green"].freeze
p colors.frozen?

begin
  colors << "blue"
rescue FrozenError => e
  puts e.message
end

p colors
true
can't modify frozen Array: ["red", "green"]
["red", "green"]

Freezing is permanent: there is no unfreeze. If you need a changeable version, make a copy with dup, which returns an unfrozen copy:

ruby · try it yourself
base = "draft".freeze
copy = base.dup
copy << " v2"
p copy
p copy.frozen?
p base.clone.frozen?   # clone keeps the frozen state
"draft v2"
false
true

Already-frozen values

Some objects are always frozen, because they are unique values that never change:

ruby · try it yourself
p 42.frozen?
p 3.14.frozen?
p :symbol.frozen?
p nil.frozen?
p true.frozen?
p (1..5).frozen?
p "literal".frozen?
true
true
true
true
true
true
false

String literals are not frozen by default — yet. See the magic comment below.

Freezing is shallow

freeze protects the object itself, but not the objects inside it:

ruby · try it yourself
config = {name: "app", tags: ["web"]}.freeze

begin
  config[:debug] = true
rescue FrozenError
  puts "can't add a key"
end

config[:tags] << "api"     # the inner array is NOT frozen
p config
can't add a key
{name: "app", tags: ["web", "api"]}

For a deep freeze, freeze the inner objects as well:

ruby · try it yourself
def deep_freeze(obj)
  case obj
  when Hash then obj.each_value { |v| deep_freeze(v) }
  when Array then obj.each { |v| deep_freeze(v) }
  end
  obj.freeze
end

settings = deep_freeze({db: {hosts: ["a", "b"]}, mode: "prod"})
p settings.dig(:db, :hosts).frozen?
p settings[:mode].frozen?

begin
  settings[:db][:hosts] << "c"
rescue FrozenError => e
  puts e.class
end
true
true
FrozenError

Frozen constants

A constant can still be modified in place if its value is mutable — freeze it to make it truly constant:

ruby · try it yourself
WEEKDAYS = %w[mon tue wed thu fri].freeze
LIMITS = {upload_mb: 10, users: 50}.freeze

p WEEKDAYS.include?("wed")
begin
  LIMITS[:users] = 9999
rescue FrozenError
  puts "LIMITS is protected"
end
true
LIMITS is protected

Tip: Freezing collection constants is standard practice in Ruby code bases. Tools like RuboCop even warn when you forget it.

The frozen_string_literal magic comment

Adding # frozen_string_literal: true as the first line of a file makes every string literal in that file frozen. Ruby can then reuse one object for identical literals, saving memory:

ruby · try it yourself
# frozen_string_literal: true

greeting = "hello"
p greeting.frozen?
p "same".equal?("same")

begin
  greeting << "!"
rescue FrozenError => e
  puts e.message
end

mutable = +"hello"      # unary + gives an unfrozen copy
mutable << "!"
p mutable
p "dynamic #{1 + 1}".frozen?
true
true
can't modify frozen String: "hello"
"hello!"
false

Interpolated strings are new objects each time, so they are not frozen.

Note: In Ruby 3.4, string literals in files without the magic comment are "chilled": mutating them still works but can emit a deprecation warning. A future Ruby is expected to make frozen literals the default, so writing code that doesn't mutate literals is the safe path.

Immutable objects of your own

Freeze an object at the end of initialize to make it immutable — or use Data, which does this for you:

ruby · try it yourself
class Color
  attr_reader :r, :g, :b

  def initialize(r, g, b)
    @r, @g, @b = r, g, b
    freeze
  end

  def lighter(amount = 20)
    Color.new(*[r, g, b].map { |c| [c + amount, 255].min })
  end

  def to_s = format("#%02X%02X%02X", r, g, b)
end

teal = Color.new(0, 128, 128)
puts teal
puts teal.lighter
puts teal.lighter(200)

begin
  teal.instance_variable_set(:@r, 255)
rescue FrozenError
  puts "teal stays #{teal}"
end
#008080
#149494
#C8FFFF
teal stays #008080

Instead of changing an object, methods like lighter return a new one. This style is easier to reason about: a value you hold can never change behind your back.

Summary

Action Result
obj.freeze obj becomes immutable (shallow)
obj.frozen? is it frozen?
obj.dup unfrozen shallow copy
obj.clone copy that keeps frozen state
+"str" guaranteed mutable string
-"str" frozen, deduplicated string
# frozen_string_literal: true all literals in the file frozen

Test yourself

What does ["a"].freeze << "b" raise?

  1. NoMethodError
  2. FrozenError
  3. ArgumentError
  4. Nothing

Given h = {list: [1]}.freeze, does h[:list] << 2 work?

  1. No, FrozenError
  2. Yes, freezing is shallow
  3. Only with dup
  4. It silently does nothing

Which copy method returns an unfrozen copy?

  1. clone
  2. dup
  3. freeze
  4. itself