Bird
0
0

Given this Ruby code, what will be the output?

hard📝 Application Q15 of 15
Ruby - Class Methods and Variables
Given this Ruby code, what will be the output?
hash = {a: [1, 2], b: [3, 4]}
hash.freeze
hash[:a] << 5
puts hash[:a].inspect
What does this tell us about freezing objects?
ARuntimeError: can't modify frozen Hash
B[1, 2] - freeze prevents any changes including nested objects
C[1, 2, 5] - freeze prevents changing the hash keys but not the objects inside
DSyntaxError due to invalid hash modification
Step-by-Step Solution
Solution:
  1. Step 1: Understand freezing the hash

    The hash object is frozen, so its structure (keys and values) cannot be changed directly.
  2. Step 2: Analyze modification of nested array

    The value for key :a is an array, which is not frozen. Modifying this array with << 5 is allowed.
  3. Step 3: Observe the output

    The array now contains [1, 2, 5], showing that freezing the hash does not freeze nested objects.
  4. Final Answer:

    [1, 2, 5] - freeze prevents changing the hash keys but not the objects inside -> Option C
  5. Quick Check:

    Freeze is shallow = nested objects can change [OK]
Quick Trick: Freeze is shallow; nested objects stay mutable unless frozen [OK]
Common Mistakes:
  • Assuming freeze affects nested objects
  • Expecting runtime error on nested modification
  • Confusing hash freezing with deep freeze

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes