0
0
Rubyprogramming~20 mins

String freezing for immutability in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby String Freeze Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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
ATypeError
BFrozenError
Chello world
Dhello
Attempts:
2 left
💡 Hint
Frozen strings cannot be modified. What error does Ruby raise when you try?
🧠 Conceptual
intermediate
1:30remaining
Why freeze a string in Ruby?
Which of the following is the main reason to freeze a string in Ruby?
ATo make the string immutable and prevent accidental changes
BTo convert the string to uppercase automatically
CTo allow the string to be garbage collected faster
DTo enable string interpolation
Attempts:
2 left
💡 Hint
Think about what freezing means in everyday life: making something fixed or unchangeable.
Predict Output
advanced
2: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
A
database
data
B
data
database
C
FrozenError
FrozenError
D
datadata
base
Attempts:
2 left
💡 Hint
Duplicating a frozen string creates a new unfrozen copy.
🔧 Debug
advanced
2: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")
AArgumentError because freeze takes no arguments
BNo error, prints 'test_end'
CTypeError because << is not defined for frozen strings
DFrozenError because the string is frozen before modification
Attempts:
2 left
💡 Hint
Freezing a string means you cannot change it afterwards.
🚀 Application
expert
2: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"
A3
B5
CRaises FrozenError
D4
Attempts:
2 left
💡 Hint
What happens if you try to add an element to a frozen array?