Bird
0
0

Given a hash prices = { apple: 2, banana: 1, orange: 3 }, how can you use inject to calculate the total price?

hard📝 Application Q8 of 15
Ruby - Enumerable and Collection Processing
Given a hash prices = { apple: 2, banana: 1, orange: 3 }, how can you use inject to calculate the total price?
Aprices.inject(0) { |sum, price| sum * price }
Bprices.inject { |sum, price| sum + price }
Cprices.inject(1) { |sum, (fruit, price)| sum + fruit }
Dprices.inject(0) { |sum, (_, price)| sum + price }
Step-by-Step Solution
Solution:
  1. Step 1: Understand hash iteration with inject

    Inject on hash yields key-value pairs as two-element arrays, so block parameters should unpack key and value.
  2. Step 2: Sum only the values starting from 0

    prices.inject(0) { |sum, (_, price)| sum + price } correctly unpacks key and price, sums prices starting at 0.
  3. Final Answer:

    prices.inject(0) { |sum, (_, price)| sum + price } -> Option D
  4. Quick Check:

    Sum hash values with inject by unpacking pairs [OK]
Quick Trick: Unpack key,value pairs in block to sum hash values [OK]
Common Mistakes:
  • Not unpacking key-value pairs correctly
  • Trying to add keys instead of values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes