Bird
0
0

You have two hashes representing inventory counts:

hard📝 Application Q8 of 15
Ruby - Hashes

You have two hashes representing inventory counts:

stock1 = {apples: 10, oranges: 5}
stock2 = {oranges: 7, bananas: 3}

How can you create a new hash that sums the counts for overlapping keys?

AUse <code>stock1 + stock2</code>
BUse <code>stock1.update(stock2)</code>
CUse <code>stock1.merge(stock2)</code>
DUse <code>stock1.merge(stock2) { |key, old, new| old + new }</code>
Step-by-Step Solution
Solution:
  1. Step 1: Understand merge with block

    Using merge with a block lets you define how to combine values for duplicate keys.
  2. Step 2: Apply block to sum values

    The block { |key, old, new| old + new } sums counts for overlapping keys like :oranges.
  3. Final Answer:

    Use stock1.merge(stock2) { |key, old, new| old + new } -> Option D
  4. Quick Check:

    merge with block combines values for duplicate keys [OK]
Quick Trick: merge with block customizes value merging [OK]
Common Mistakes:
  • Using update which overwrites values
  • Using merge without block loses old values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes