Bird
0
0

Why does Ruby allow both symbol and string keys in hashes, and what is a key difference in their behavior?

hard📝 Conceptual Q10 of 15
Ruby - Hashes
Why does Ruby allow both symbol and string keys in hashes, and what is a key difference in their behavior?
ASymbols are immutable and reused, strings are mutable and unique objects
BSymbols and strings behave identically in hashes
CSymbols are slower to access than strings
DStrings are automatically converted to symbols in hashes
Step-by-Step Solution
Solution:
  1. Step 1: Understand symbol immutability

    Symbols are immutable and reused, meaning the same symbol object is used everywhere.
  2. Step 2: Understand string mutability

    Strings are mutable and each string literal creates a new object, so keys differ by object identity.
  3. Final Answer:

    Symbols are immutable and reused, strings are mutable and unique objects -> Option A
  4. Quick Check:

    Symbols immutable, strings mutable [OK]
Quick Trick: Symbols are immutable; strings are mutable objects [OK]
Common Mistakes:
  • Assuming symbols and strings behave the same
  • Thinking strings convert automatically to symbols
  • Believing symbols are slower than strings

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes