Immutable data with freeze in Ruby - Time & Space Complexity
We want to see how using freeze to make data unchangeable affects how long a program takes to run.
Specifically, we ask: does freezing data change the work done when we use it?
Analyze the time complexity of the following code snippet.
array = [1, 2, 3, 4, 5]
array.freeze
array.each do |num|
puts num
end
This code freezes an array to make it unchangeable, then prints each number in it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element of the array with
each. - How many times: Once for each element in the array (n times).
As the array gets bigger, the program prints more numbers, so it does more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print operations |
| 100 | 100 print operations |
| 1000 | 1000 print operations |
Pattern observation: The work grows directly with the number of items. Freezing does not add extra repeated work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items in the array, even when it is frozen.
[X] Wrong: "Freezing the array makes the program slower because it adds extra work every time we use the array."
[OK] Correct: Freezing only happens once and does not repeat during the loop. Using the frozen array is just as fast as using a normal array.
Understanding how immutable data affects performance helps you write safer code without surprises about speed. It shows you can think about both correctness and efficiency together.
"What if we replaced each with a nested loop over the array? How would the time complexity change?"
Practice
freeze method do to an object in Ruby?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]
- Thinking freeze deletes the object
- Confusing freeze with duplication
- Assuming freeze makes object mutable
name in Ruby?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]
- Using freeze as a standalone function
- Trying to assign frozen = true
- Omitting dot before freeze
arr = [1, 2, 3] arr.freeze arr << 4 puts arr.inspect
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]
- Assuming frozen array can still be changed
- Expecting silent failure or no error
- Confusing output with syntax error
str = "hello" str.freeze str[0] = 'H' puts str
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]
- Thinking string changes silently fail
- Expecting output "Hello" without error
- Confusing syntax error with runtime error
original = [10, 20, 30].freeze # Your code here to add 40
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]
- Trying to modify frozen array directly
- Using non-existent freeze(false) method
- Assuming push works on frozen array
Ready to prove it?
Pass the test and this pattern moves unknown
