Bird
0
0

Why do Ruby hashes allow keys of many types (symbols, strings, numbers) but symbols are preferred?

hard📝 Conceptual Q10 of 15
Ruby - Hashes
Why do Ruby hashes allow keys of many types (symbols, strings, numbers) but symbols are preferred?
ASymbols are immutable and memory-efficient keys
BStrings are faster than symbols as keys
CNumbers cannot be used as hash keys
DSymbols automatically convert to strings
Step-by-Step Solution
Solution:
  1. Step 1: Understand symbol properties

    Symbols are immutable and reused, so they save memory and speed up key comparisons.
  2. Step 2: Compare with strings and numbers

    Strings are mutable and create new objects, numbers can be keys but symbols are more efficient for identifiers.
  3. Final Answer:

    Symbols are immutable and memory-efficient keys -> Option A
  4. Quick Check:

    Symbols = efficient, immutable keys = A [OK]
Quick Trick: Use symbols as keys for efficiency and immutability [OK]
Common Mistakes:
MISTAKES
  • Thinking strings are faster than symbols
  • Believing numbers cannot be keys
  • Assuming symbols convert to strings automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes