Freezing data makes it unchangeable. This helps keep your program safe from accidental changes.
Immutable data with freeze in Ruby
Introduction
Syntax
Ruby
object.freezeCalling freeze on an object stops it from being changed.
If you try to change a frozen object, Ruby raises an error.
Examples
Ruby
name = "Alice" name.freeze name << " Smith" # This will cause an error
Ruby
numbers = [1, 2, 3] numbers.freeze numbers << 4 # This will cause an error
Ruby
config = { theme: "dark", font: "Arial" }
config.freeze
config[:theme] = "light" # ErrorSample 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]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.
Practice
1. What does the
freeze method do to an object in Ruby?easy
Solution
Step 1: Understand the purpose of
Thefreezefreezemethod is used to make an object immutable, meaning it cannot be changed after freezing.Step 2: Identify the effect on the object
Once frozen, any attempt to modify the object will raise an error, so it prevents further changes.Final Answer:
Prevents any further modifications to the object -> Option AQuick Check:
freezemakes object immutable = Prevents changes [OK]
Hint: Freeze means no changes allowed after calling it [OK]
Common Mistakes:
- Thinking freeze deletes the object
- Confusing freeze with duplication
- Assuming freeze makes object mutable
2. Which of the following is the correct way to freeze a string
name in Ruby?easy
Solution
Step 1: Recall Ruby method call syntax
In Ruby, to call a method on an object, use dot notation likeobject.method().Step 2: Identify the correct freeze syntax
The correct way to freeze the stringnameisname.freeze(). Other options are invalid syntax or incorrect usage.Final Answer:
name.freeze() -> Option CQuick Check:
Method call with dot and parentheses = Correct freeze syntax [OK]
Hint: Use dot notation: object.freeze() to freeze [OK]
Common Mistakes:
- Using freeze as a standalone function
- Trying to assign frozen = true
- Omitting dot before freeze
3. What will be the output of this Ruby code?
arr = [1, 2, 3] arr.freeze arr << 4 puts arr.inspect
medium
Solution
Step 1: Understand freezing the array
The arrayarris frozen usingarr.freeze, making it immutable.Step 2: Analyze the modification attempt
Trying to append4witharr << 4will raise a RuntimeError because the array is frozen and cannot be changed.Final Answer:
RuntimeError: can't modify frozen Array -> Option BQuick Check:
Frozen object + modification = RuntimeError [OK]
Hint: Modifying frozen object causes RuntimeError [OK]
Common Mistakes:
- Assuming frozen array can still be changed
- Expecting silent failure or no error
- Confusing output with syntax error
4. Identify the error in this Ruby code snippet:
str = "hello" str.freeze str[0] = 'H' puts str
medium
Solution
Step 1: Recognize string freezing effect
The stringstris frozen, so it cannot be changed afterstr.freeze.Step 2: Understand the attempted modification
Trying to change the first character withstr[0] = 'H'raises a RuntimeError because the string is frozen.Final Answer:
RuntimeError: can't modify frozen String -> Option AQuick Check:
Frozen string + modification = RuntimeError [OK]
Hint: Frozen string cannot be changed, causes RuntimeError [OK]
Common Mistakes:
- Thinking string changes silently fail
- Expecting output "Hello" without error
- Confusing syntax error with runtime error
5. Given this code, what is the best way to safely modify a frozen array without error?
original = [10, 20, 30].freeze # Your code here to add 40
hard
Solution
Step 1: Understand frozen array cannot be changed
The arrayoriginalis frozen, so direct modification like<<orpushwill cause errors.Step 2: Use duplication to create a modifiable copy
Usingoriginal.dupcreates a new unfrozen copy. Then appending40to this copy is allowed.Step 3: Assign the modified copy back
Assigning the new array with40added back tooriginalvariable safely updates it without error.Final Answer:
original = original.dup << 40 -> Option DQuick Check:
Duplicate frozen object before modifying = Safe change [OK]
Hint: Duplicate frozen object before changing it [OK]
Common Mistakes:
- Trying to modify frozen array directly
- Using non-existent freeze(false) method
- Assuming push works on frozen array
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
