Frozen Objects & Immutability in Ruby
Understand frozen objects in Ruby, how to prevent mutation, and why immutability matters for safe and predictable code.
freeze & frozen?
Calling `freeze` on an object permanently prevents any mutation. Once frozen, the object cannot be modified — any attempt raises a `FrozenError`. `frozen?` lets you check the state. Freeze is shallow — nested objects must be frozen separately.
1. Freezing Strings
Freeze a string to prevent accidental mutation.
2. Freezing Arrays & Hashes
Freeze collections — but beware of shallow freeze.
3. Always-Frozen Objects
Integers, symbols, true, false, and nil are always frozen.
Frozen String Literals
Ruby 2.3+ introduced the `# frozen_string_literal: true` magic comment. When placed at the top of a file, every string literal in that file is automatically frozen — saving memory and preventing accidental mutation. Rails enables this by default in all generated files.
1. The frozen_string_literal Magic Comment
Freeze all string literals in a file with one comment.
2. dup vs clone on Frozen Objects
dup creates an unfrozen copy; clone preserves the frozen state.
Immutable Value Objects
An immutable value object is an object whose state never changes after initialisation. It is safe to share across threads, use as a hash key, and cache freely. Ruby provides several patterns to achieve this — from manual freeze to `Data` (Ruby 3.2+).
1. Freeze in initialize
Call freeze at the end of the constructor to lock the object.
2. Data — Built-in Immutable Value Object (Ruby 3.2+)
Use Data.define for concise, frozen value objects.
3. Struct vs Data — When to Use Each
Struct is mutable; Data is immutable. Choose based on your intent.
Immutability Best Practices
Immutability is not just about `freeze` — it is a design philosophy. Immutable objects are thread-safe by default, free to share without defensive copying, and simpler to reason about.
1. Defensive Copies & Returning Frozen Constants
Protect mutable internal state from outside mutation.
2. Immutability & Thread Safety
Frozen objects are safe to share across threads without locks.