Bird
0
0

What happens if you use each on a hash with duplicate keys in the block variable assignment?

hard📝 Conceptual Q10 of 15
Ruby - Loops and Iteration
What happens if you use each on a hash with duplicate keys in the block variable assignment?
AThe last key-value pair overwrites previous ones in the block variable
BEach key-value pair is yielded separately, duplicates do not affect iteration
CRuby raises an error due to duplicate keys
DOnly unique keys are yielded once
Step-by-Step Solution
Solution:
  1. Step 1: Understand hash iteration behavior

    Hashes yield each key-value pair independently, even if keys appear duplicated in data structure.
  2. Step 2: Clarify effect of duplicate keys

    Ruby hashes cannot have duplicate keys; if duplicates exist in source, last wins, but iteration yields each pair once.
  3. Final Answer:

    Each key-value pair is yielded separately, duplicates do not affect iteration -> Option B
  4. Quick Check:

    Hash each yields all pairs; duplicates handled before iteration [OK]
Quick Trick: Hashes have unique keys; each yields pairs one by one [OK]
Common Mistakes:
MISTAKES
  • Expecting error on duplicate keys
  • Thinking iteration merges duplicates
  • Confusing block variable behavior with hash uniqueness

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes