Challenge - 5 Problems
Ruby String 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 this Ruby code with frozen string?
Consider the following Ruby code snippet. What will it print?
Ruby
str = "hello" str.freeze begin str << " world" rescue => e puts e.class end
Attempts:
2 left
💡 Hint
Frozen strings cannot be modified. What error does Ruby raise when you try?
✗ Incorrect
When a string is frozen in Ruby, any attempt to modify it raises a FrozenError. The code tries to append to the frozen string, so it raises FrozenError.
🧠 Conceptual
intermediate1:30remaining
Why freeze a string in Ruby?
Which of the following is the main reason to freeze a string in Ruby?
Attempts:
2 left
💡 Hint
Think about what freezing means in everyday life: making something fixed or unchangeable.
✗ Incorrect
Freezing a string makes it immutable, so it cannot be changed after freezing. This helps avoid bugs from accidental modifications.
❓ Predict Output
advanced2:00remaining
What is the output of this Ruby code with frozen string and dup?
What will this Ruby code print?
Ruby
str = "data" frozen_str = str.freeze copy = frozen_str.dup copy << "base" puts copy puts frozen_str
Attempts:
2 left
💡 Hint
Duplicating a frozen string creates a new unfrozen copy.
✗ Incorrect
The frozen string cannot be changed, but dup creates a new unfrozen string copy. So modifying copy works, original stays frozen.
🔧 Debug
advanced2:00remaining
Identify the error in this Ruby code using frozen strings
What error will this code produce and why?
Ruby
def add_suffix(s) s.freeze s << "_end" end puts add_suffix("test")
Attempts:
2 left
💡 Hint
Freezing a string means you cannot change it afterwards.
✗ Incorrect
The method freezes the string then tries to append to it, which raises FrozenError.
🚀 Application
expert2:30remaining
How many items are in the resulting array after freezing strings?
Given this Ruby code, how many elements does the array contain after execution?
Ruby
arr = [] 3.times do |i| s = "item#{i}" arr << s.freeze end arr << "item3" arr.freeze arr << "item4"
Attempts:
2 left
💡 Hint
What happens if you try to add an element to a frozen array?
✗ Incorrect
The array is frozen before the last push, so trying to add "item4" raises FrozenError.