0
0
Rubyprogramming~5 mins

Frozen objects in Ruby

Choose your learning style9 modes available
Introduction

Freezing an object in Ruby means making it unchangeable. This helps keep data safe from accidental changes.

When you want to make sure a configuration value never changes during the program.
When sharing data between parts of a program and want to avoid accidental edits.
When you want to improve performance by preventing unnecessary copies of objects.
When debugging to catch unexpected changes to important objects.
Syntax
Ruby
object.freeze

Calling freeze on an object makes it immutable.

If you try to change a frozen object, Ruby raises a FrozenError.

Examples
Freezing a string prevents adding more text to it.
Ruby
str = "hello"
str.freeze
str << " world"  # This will cause an error
Freezing an array stops changing its elements.
Ruby
arr = [1, 2, 3]
arr.freeze
arr[0] = 10  # This will cause an error
Freezing a number does nothing because numbers can't be changed anyway.
Ruby
num = 100
num.freeze
# Numbers are already immutable, so freezing has no effect
Sample Program

This program freezes a string and then tries to change it. Ruby raises an error, which we catch and print. Finally, it prints the original string.

Ruby
name = "Alice"
name.freeze

begin
  name << " Smith"
rescue => e
  puts "Error: #{e.message}"
end

puts name
OutputSuccess
Important Notes

Freezing only affects the object itself, not objects inside it. For example, freezing an array does not freeze the objects inside the array.

You can check if an object is frozen by calling object.frozen?.

Summary

Freezing makes objects unchangeable to protect data.

Trying to change a frozen object causes an error.

Use freeze to keep important data safe from accidental changes.