Bird
0
0

How can you reopen the Hash class to add a method keys_to_strings that returns a new hash with all keys converted to strings?

hard📝 Application Q9 of 15
Ruby - Class Methods and Variables
How can you reopen the Hash class to add a method keys_to_strings that returns a new hash with all keys converted to strings?
Aclass Hash def keys_to_strings map { |k, v| [k.to_s, v] }.to_h end end
Bdef Hash.keys_to_strings map { |k, v| [k.to_s, v] }.to_h end
Cclass Hash.new def keys_to_strings map { |k, v| [k.to_s, v] }.to_h end end
Dmodule Hash def keys_to_strings map { |k, v| [k.to_s, v] }.to_h end end
Step-by-Step Solution
Solution:
  1. Step 1: Correctly reopen Hash class

    class Hash def keys_to_strings map { |k, v| [k.to_s, v] }.to_h end end reopens Hash and adds an instance method using valid syntax.
  2. Step 2: Verify method implementation

    The method uses map and to_h to convert keys to strings correctly.
  3. Final Answer:

    class Hash def keys_to_strings map { |k, v| [k.to_s, v] }.to_h end end -> Option A
  4. Quick Check:

    Reopen Hash with instance method for key conversion [OK]
Quick Trick: Use map and to_h inside reopened class methods [OK]
Common Mistakes:
  • Defining class methods instead of instance methods
  • Using module instead of class

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes