Bird
0
0

Given this Ruby hash, what is the error in accessing the value?

medium📝 Debug Q14 of 15
Ruby - Hashes
Given this Ruby hash, what is the error in accessing the value?
settings = { 'theme' => 'dark', :font_size => 12 }
puts settings.fetch(:theme)
AKeyError because :theme symbol key does not exist.
BNo error; outputs 'dark'.
CSyntaxError due to mixed key types.
DRuntimeError because font_size is a symbol.
Step-by-Step Solution
Solution:
  1. Step 1: Check hash keys and access

    The hash has a string key 'theme' and a symbol key :font_size.
  2. Step 2: Identify the accessed key and result

    Accessing settings.fetch(:theme) looks for symbol :theme, which does not exist, raising a KeyError.
  3. Final Answer:

    KeyError because :theme symbol key does not exist. -> Option A
  4. Quick Check:

    Access key type must match stored key type [OK]
Quick Trick: Match key type exactly when accessing hash values [OK]
Common Mistakes:
MISTAKES
  • Assuming string and symbol keys are interchangeable
  • Expecting no error when accessing missing key
  • Confusing syntax errors with key access errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes