Immutability
suggest changeIn Ruby, almost all objects are mutable by default. Strings, arrays, hashes, and custom class instances can have their internal state altered in-place. Immutability—ensuring an object cannot be modified after creation—helps prevent bugs caused by unintended shared mutations, improves thread safety, and simplifies reasoning about code.
Freezing Objects with freeze
You can make any object immutable by invoking its freeze method. Once frozen, any attempt to modify the object raises a FrozenError (a subclass of RuntimeError).
You can check whether an object is frozen using frozen?:
str = "hello"
puts str.frozen? # false
str.freeze
puts str.frozen? # true
# Attempting to mutate a frozen object raises FrozenError
begin
str << " world"
rescue FrozenError => e
puts "Error: #{e.message}"
end
false
true
Error: can't modify frozen String: "hello"
Shallow vs. Deep Freezing
Calling freeze only freezes the immediate object reference (shallow freeze). If an array or hash contains other mutable objects, those inner objects can still be modified:
list = ["apple", "banana"].freeze
# You cannot add or remove items from list:
# list << "cherry" # raises FrozenError
# But individual elements remain mutable:
list[0].upcase!
puts list[0] # "APPLE"
To achieve deep immutability, freeze the container and each nested element recursively:
def deep_freeze(object)
case object
when Hash
object.each { |k, v| deep_freeze(k); deep_freeze(v) }
when Array, Set
object.each { |element| deep_freeze(element) }
end
object.freeze
end
config = deep_freeze({
database: {
host: "localhost",
port: 5432
}
})
puts config.frozen? # true
puts config[:database].frozen? # true
puts config[:database][:host].frozen? # true
Frozen String Literals
To prevent repeated string allocation and enforce immutability across an entire file, add the # frozen_string_literal: true magic comment as the first line of the file:
# frozen_string_literal: true
greeting = "hello"
puts greeting.frozen? # true
# If mutation is needed, explicitly duplicate the string:
mutable_copy = +"hello" # or "hello".dup
mutable_copy << " world"
puts mutable_copy # "hello world"
The unary + operator returns an unfrozen copy of a string, while the unary - operator returns a frozen copy (and deduplicates it).
Immutable Value Objects with Data.define (Ruby 3.2+)
Ruby 3.2 introduced Data.define, which creates lightweight, immutable value objects:
Point = Data.define(:x, :y)
p1 = Point.new(10, 20)
puts p1.x # 10
puts p1.y # 20
puts p1.frozen? # true
# Trying to set an attribute raises NoMethodError because no setter exists:
# p1.x = 30
# Use `with` to create a new instance with updated values:
p2 = p1.with(y: 50)
puts "p1: x=#{p1.x}, y=#{p1.y}"
puts "p2: x=#{p2.x}, y=#{p2.y}"
10
20
true
p1: x=10, y=20
p2: x=10, y=50
Non-Destructive Operations
An immutable programming style avoids in-place mutators (!) in favor of methods that return new instances:
numbers = [3, 1, 4, 1, 5]
# Mutating:
# numbers.sort!
# Non-destructive (returns a new array):
sorted_numbers = numbers.sort
puts "Original: #{numbers}"
puts "Sorted: #{sorted_numbers}"
# Merging hashes non-destructively:
defaults = { timeout: 30, retries: 3 }
custom = { timeout: 60 }
settings = defaults.merge(custom)
puts "Defaults: #{defaults}"
puts "Settings: #{settings}"
Original: [3, 1, 4, 1, 5]
Sorted: [1, 1, 3, 4, 5]
Defaults: {timeout: 30, retries: 3}
Settings: {timeout: 60, retries: 3}