Challenge - 5 Problems
Ruby Freeze Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of freezing a string and then modifying it?
Consider the following Ruby code. What will be the output when it is run?
Ruby
str = "hello" str.freeze begin str << " world" rescue => e puts e.class end
Attempts:
2 left
💡 Hint
Freezing an object prevents modifications. What happens if you try to change a frozen string?
✗ Incorrect
In Ruby, freezing a string prevents it from being modified. Trying to append to a frozen string raises a RuntimeError.
❓ Predict Output
intermediate2:00remaining
What happens when you freeze an array and try to modify it?
Look at this Ruby code. What will be printed when it runs?
Ruby
arr = [1, 2, 3] arr.freeze begin arr.push(4) rescue => e puts e.class end
Attempts:
2 left
💡 Hint
Freezing an array stops changes like adding elements. What error is raised if you try?
✗ Incorrect
A frozen array cannot be changed. Trying to push a new element raises a RuntimeError.
🧠 Conceptual
advanced2:00remaining
Which statement about freezing nested objects is true?
Given a frozen array that contains other arrays, which statement is correct?
Attempts:
2 left
💡 Hint
Think about whether freeze applies recursively or only to the object itself.
✗ Incorrect
In Ruby, freeze only affects the object it is called on. Nested objects remain mutable unless frozen separately.
❓ Predict Output
advanced2:00remaining
What is the output when freezing a hash and modifying a nested array value?
Analyze this Ruby code and determine the output:
Ruby
h = {a: [1, 2], b: [3, 4]}
h.freeze
begin
h[:a] << 5
rescue => e
puts e.class
end
puts h[:a].inspectAttempts:
2 left
💡 Hint
Freezing a hash stops changing keys or values, but what about modifying the objects inside the hash?
✗ Incorrect
The hash is frozen, so you cannot add or remove keys, but the arrays inside are still mutable and can be changed.
🔧 Debug
expert3:00remaining
Why does this code raise an error when freezing a nested structure?
This Ruby code tries to freeze a nested array structure. Why does it raise an error?
Ruby
def deep_freeze(obj) obj.freeze if obj.is_a?(Array) obj.each { |e| deep_freeze(e) } elsif obj.is_a?(Hash) obj.each { |k, v| deep_freeze(k); deep_freeze(v) } end end nested = [1, [2, 3], {a: 4}] deep_freeze(nested) nested[1] << 5
Attempts:
2 left
💡 Hint
Check what deep_freeze does to nested arrays and what happens when you try to modify a frozen array.
✗ Incorrect
The deep_freeze method freezes the entire nested structure recursively. Trying to modify nested[1], which is a frozen array, raises a RuntimeError.