Bird
0
0

Identify the error in this Ruby code snippet:

medium📝 Debug Q6 of 15
Ruby - File IO

Identify the error in this Ruby code snippet:

require 'json'
json_str = '{"a":1, "b":2}'
obj = JSON.parse(json_str)
puts obj[:a]
AJSON string is invalid
BUsing symbol key :a instead of string key "a"
CMissing require 'json' statement
DUsing puts instead of print
Step-by-Step Solution
Solution:
  1. Step 1: Understand JSON.parse output keys

    JSON.parse returns a Ruby hash with string keys, not symbols.
  2. Step 2: Check key access method

    Accessing obj[:a] uses a symbol key, which does not exist in the hash, resulting in nil.
  3. Final Answer:

    Using symbol key :a instead of string key "a" -> Option B
  4. Quick Check:

    JSON keys are strings, access with string keys [OK]
Quick Trick: Access parsed JSON keys with strings, not symbols [OK]
Common Mistakes:
  • Using symbol keys to access parsed JSON
  • Forgetting to require 'json'
  • Incorrect JSON string format

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes