Bird
0
0

Given a hash h = {a: 1, b: 2, c: 3}, how can you create a new hash with keys and their values doubled?

hard📝 Application Q8 of 15
Ruby - Hashes
Given a hash h = {a: 1, b: 2, c: 3}, how can you create a new hash with keys and their values doubled?
Ah.each_with_object({}) { |(k,v), new_h| new_h[k] = v * 2 }
Bh.keys.map { |k| k * 2 }
Ch.values.each { |v| v * 2 }
Dh.map { |k, v| [k * 2, v] }.to_h
Step-by-Step Solution
Solution:
  1. Step 1: Understand the goal

    Create a new hash with the same keys but values doubled.
  2. Step 2: Analyze each option

    B uses each_with_object to build a new hash with doubled values correctly. A returns an array of doubled keys. C does not build a hash. D doubles keys, not values.
  3. Final Answer:

    h.each_with_object({}) { |(k,v), new_h| new_h[k] = v * 2 } -> Option A
  4. Quick Check:

    Use each_with_object to build new hash with transformed values [OK]
Quick Trick: Use each_with_object to build new hash with changed values [OK]
Common Mistakes:
MISTAKES
  • Doubling keys instead of values
  • Using map without to_h
  • Not building a new hash

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes