Bird
0
0

How can you safely modify a frozen hash h = {x: 1, y: 2}.freeze by adding a new key-value pair?

hard📝 Application Q9 of 15
Ruby - Class Methods and Variables
How can you safely modify a frozen hash h = {x: 1, y: 2}.freeze by adding a new key-value pair?
Ah[:z] = 3
Bh.merge!(z: 3)
Ch.update(z: 3)
Dh.merge(z: 3)
Step-by-Step Solution
Solution:
  1. Step 1: Recognize frozen hash cannot be changed

    Direct modification like h[:z] = 3 or mutating methods like merge! or update raises error.
  2. Step 2: Use non-destructive merge method

    h.merge(z: 3) returns a new hash with added pair, original remains frozen.
  3. Final Answer:

    h.merge(z: 3) -> Option D
  4. Quick Check:

    Modify frozen hash safely = merge returns new hash [OK]
Quick Trick: Use merge to add keys without modifying frozen hash [OK]
Common Mistakes:
  • Trying to update frozen hash directly
  • Using mutating merge! on frozen hash
  • Expecting update to work on frozen hash

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes