Bird
0
0

You want to reopen the Hash class to add a method symbolize_keys that returns a new hash with all string keys converted to symbols. Which code correctly does this?

hard📝 Application Q15 of 15
Ruby - Class Methods and Variables
You want to reopen the Hash class to add a method symbolize_keys that returns a new hash with all string keys converted to symbols. Which code correctly does this?
Aclass Hash def symbolize_keys each_with_object({}) do |(k, v), h| h[k.to_sym] = v end end end
Bclass Hash def symbolize_keys map { |k, v| [k.to_sym, v] } end end
Cclass Hash def symbolize_keys keys.map(&:to_sym) end end
Dclass Hash def symbolize_keys self.transform_keys(&:to_sym) end end
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    We want a method that returns a new hash with string keys converted to symbols.
  2. Step 2: Check each option's correctness

    class Hash def symbolize_keys each_with_object({}) do |(k, v), h| h[k.to_sym] = v end end end manually builds a new hash but misses handling non-string keys safely. class Hash def symbolize_keys map { |k, v| [k.to_sym, v] } end end returns an array, not a hash. class Hash def symbolize_keys keys.map(&:to_sym) end end returns only keys as symbols, not a hash. class Hash def symbolize_keys self.transform_keys(&:to_sym) end end uses transform_keys(&:to_sym), a built-in method that correctly returns a new hash with symbol keys.
  3. Final Answer:

    class Hash def symbolize_keys self.transform_keys(&:to_sym) end end -> Option D
  4. Quick Check:

    Use transform_keys(&:to_sym) for symbol keys [OK]
Quick Trick: Use transform_keys(&:to_sym) to convert keys easily [OK]
Common Mistakes:
  • Returning array instead of hash
  • Not returning a new hash
  • Ignoring keys that are not strings

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes