Bird
0
0

When parsing JSON in Ruby, what happens if the JSON string contains duplicate keys?

hard📝 Conceptual Q10 of 15
Ruby - File IO

When parsing JSON in Ruby, what happens if the JSON string contains duplicate keys?

AThe last key-value pair overwrites previous ones
BAn error is raised for duplicate keys
CAll values are stored in an array under the key
DOnly the first key-value pair is kept
Step-by-Step Solution
Solution:
  1. Step 1: Understand Ruby hash behavior on duplicate keys

    Ruby hashes overwrite earlier values when duplicate keys are assigned.
  2. Step 2: Apply this to JSON.parse output

    When JSON.parse encounters duplicate keys, the last key-value pair overwrites previous ones in the resulting hash.
  3. Final Answer:

    The last key-value pair overwrites previous ones -> Option A
  4. Quick Check:

    Duplicate JSON keys = last wins in Ruby hash [OK]
Quick Trick: Duplicate keys in JSON parsed to Ruby hash overwrite earlier values [OK]
Common Mistakes:
  • Expecting error on duplicates
  • Thinking values are combined in arrays
  • Assuming first key is kept

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes