0
0
Rubyprogramming~5 mins

Immutable data with freeze in Ruby

Choose your learning style9 modes available
Introduction

Freezing data makes it unchangeable. This helps keep your program safe from accidental changes.

When you want to keep a list of settings that should never change.
When sharing data between parts of a program without risk of modification.
When you want to protect constants from being altered by mistake.
When debugging to ensure certain values remain fixed.
When working with multiple threads to avoid conflicts from data changes.
Syntax
Ruby
object.freeze

Calling freeze on an object stops it from being changed.

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

Examples
Freezing a string stops it from being changed. Trying to add text causes an error.
Ruby
name = "Alice"
name.freeze
name << " Smith"  # This will cause an error
Freezing an array stops adding or removing items.
Ruby
numbers = [1, 2, 3]
numbers.freeze
numbers << 4  # This will cause an error
Freezing a hash stops changing its keys or values.
Ruby
config = { theme: "dark", font: "Arial" }
config.freeze
config[:theme] = "light"  # Error
Sample Program

This program freezes a settings hash. When we try to change volume, Ruby raises an error. We catch and print the error message. Then we print the original volume value.

Ruby
settings = { volume: 10, brightness: 70 }
settings.freeze

begin
  settings[:volume] = 20
rescue => e
  puts "Error: #{e.message}"
end

puts settings[:volume]
OutputSuccess
Important Notes

Freezing only stops changes to the object itself, not to objects inside it. For deep immutability, freeze nested objects too.

Use freezing to protect important data but remember it cannot be undone.

Summary

Use freeze to make objects unchangeable.

Trying to change frozen objects causes errors.

Freezing helps keep data safe and predictable.