0
0
RubyHow-ToBeginner · 3 min read

How to Make Object Immutable in Ruby: Simple Guide

In Ruby, you make an object immutable by calling the freeze method on it. This prevents any further modifications to the object, making it read-only.
📐

Syntax

The freeze method is called on an object to make it immutable. Once frozen, the object cannot be changed.

  • object.freeze: Freezes the object.
  • After freezing, any attempt to modify the object raises a FrozenError.
ruby
object.freeze
💻

Example

This example shows how to freeze a string object and what happens if you try to modify it after freezing.

ruby
name = "Ruby"
name.freeze
begin
  name << "Lang"
rescue => e
  puts e.message
end
puts name
Output
can't modify frozen String Ruby
⚠️

Common Pitfalls

Freezing only prevents changes to the object itself, not to objects referenced inside it. For example, freezing an array does not freeze the elements inside it.

Also, calling freeze on immutable objects like numbers or symbols has no effect because they are already immutable.

ruby
arr = [1, [2, 3]]
arr.freeze
arr[0] = 10 rescue puts "Cannot modify frozen array"
arr[1][0] = 20 # This works because inner array is not frozen
puts arr.inspect
Output
Cannot modify frozen array [1, [20, 3]]
📊

Quick Reference

  • freeze: Makes object immutable.
  • FrozenError: Raised when modifying a frozen object.
  • Freezing is shallow; nested objects remain mutable unless frozen separately.
  • Use dup.freeze to create an immutable copy.

Key Takeaways

Use freeze to make an object immutable in Ruby.
Frozen objects raise FrozenError if modified.
Freezing is shallow; nested objects remain mutable unless frozen.
Immutable objects help prevent accidental changes and bugs.
Use dup.freeze to freeze a copy without affecting the original.