0
0
Rubyprogramming~20 mins

Frozen objects in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Frozen Object Mastery
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 this Ruby code snippet:
str = "hello".freeze
str << " world"
puts str

What will be the output or error?
Ruby
str = "hello".freeze
str << " world"
puts str
ARuntimeError: can't modify frozen String
Bhello world
CTypeError: no implicit conversion of String into Integer
Dhello
Attempts:
2 left
💡 Hint
Frozen objects cannot be changed after freezing.
Predict Output
intermediate
2:00remaining
What happens when modifying a frozen array element?
Look at this Ruby code:
arr = [1, 2, 3].freeze
arr[0] = 10
puts arr.inspect

What will be the output or error?
Ruby
arr = [1, 2, 3].freeze
arr[0] = 10
puts arr.inspect
ARuntimeError: can't modify frozen Array
B[10, 2, 3]
C[1, 2, 3]
DTypeError: no implicit conversion of Integer into String
Attempts:
2 left
💡 Hint
Freezing an array prevents changing its elements.
Predict Output
advanced
2:00remaining
What is the output when freezing a hash and modifying a nested object?
Consider this Ruby code:
h = {a: [1, 2]}
h.freeze
h[:a] << 3
puts h[:a].inspect

What will be printed or what error occurs?
Ruby
h = {a: [1, 2]}
h.freeze
h[:a] << 3
puts h[:a].inspect
A[1, 2]
B[1, 2, 3]
CRuntimeError: can't modify frozen Hash
DTypeError: no implicit conversion of Integer into String
Attempts:
2 left
💡 Hint
Freezing a hash does not freeze its nested objects.
Predict Output
advanced
2:00remaining
What error occurs when freezing a string literal and modifying it?
Analyze this Ruby code:
def modify_str(s)
  s << "!"
end

str = "hello".freeze
modify_str(str)
puts str

What will happen when running this code?
Ruby
def modify_str(s)
  s << "!"
end

str = "hello".freeze
modify_str(str)
puts str
Ahello!
BNo output, program hangs
CRuntimeError: can't modify frozen String
DTypeError: no implicit conversion of String into Integer
Attempts:
2 left
💡 Hint
Frozen strings cannot be changed even inside methods.
🧠 Conceptual
expert
3:00remaining
Why does freezing an object not freeze its nested objects in Ruby?
In Ruby, when you freeze an object like a hash or array, its nested objects remain mutable.

Why does Ruby behave this way?
ABecause freezing an object disables garbage collection for nested objects.
BBecause Ruby automatically freezes nested objects only if they are strings.
CBecause freezing an object clones all nested objects and freezes the clones instead.
DBecause freeze only marks the top-level object as immutable; nested objects are separate and must be frozen individually.
Attempts:
2 left
💡 Hint
Think about how objects and references work in Ruby.