Bird
0
0

Given the array arr = [["name", "Dave"], [:age, 40], ["city", "NY"]], which code correctly converts it into a hash with symbol keys where possible?

hard📝 Application Q15 of 15
Ruby - Hashes
Given the array arr = [["name", "Dave"], [:age, 40], ["city", "NY"]], which code correctly converts it into a hash with symbol keys where possible?
Ahash = arr.to_h
Bhash = arr.map { |k, v| [k.to_sym, v] }.to_h
Chash = arr.map { |k, v| [k, v] }.to_h
Dhash = arr.map { |k, v| [k.to_s, v] }.to_h
Step-by-Step Solution
Solution:
  1. Step 1: Understand the array structure

    The array has pairs with keys as strings or symbols. We want all keys as symbols where possible.
  2. Step 2: Convert keys to symbols

    hash = arr.map { |k, v| [k.to_sym, v] }.to_h converts each key to symbol using k.to_sym before creating the hash, ensuring keys are symbols.
  3. Step 3: Check other options

    hash = arr.to_h keeps keys as is (mixed). hash = arr.map { |k, v| [k, v] }.to_h keeps keys as is without conversion. hash = arr.map { |k, v| [k.to_s, v] }.to_h converts all keys to strings, not symbols.
  4. Final Answer:

    hash = arr.map { |k, v| [k.to_sym, v] }.to_h -> Option B
  5. Quick Check:

    Use to_sym on keys to get symbol keys [OK]
Quick Trick: Use map with to_sym on keys to get symbol keys [OK]
Common Mistakes:
  • Not converting string keys to symbols
  • Using to_s instead of to_sym
  • Assuming to_h converts keys automatically

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes