Bird
0
0

Given an array of hashes representing products with keys :name and :price, how can you use inject to find the total price of all products?

hard📝 Application Q15 of 15
Ruby - Enumerable and Collection Processing
Given an array of hashes representing products with keys :name and :price, how can you use inject to find the total price of all products?
products = [
  { name: "Book", price: 12 },
  { name: "Pen", price: 3 },
  { name: "Notebook", price: 7 }
]
Aproducts.inject { |total, product| total + product.name }
Bproducts.inject(1) { |total, product| total * product[:price] }
Cproducts.inject(0) { |total, product| total + product[:price] }
Dproducts.inject(0) { |total, product| total + product.price }
Step-by-Step Solution
Solution:
  1. Step 1: Access the price key correctly

    Each product is a hash, so access price with product[:price].
  2. Step 2: Sum prices starting at 0

    Start with 0 and add each price to get total price.
  3. Step 3: Check other options

    products.inject { |total, product| total + product.name } uses dot notation which is invalid for hashes, C multiplies prices, D uses dot notation again.
  4. Final Answer:

    products.inject(0) { |total, product| total + product[:price] } -> Option C
  5. Quick Check:

    Sum prices with inject and hash keys = B [OK]
Quick Trick: Use hash keys with [:key] inside inject block [OK]
Common Mistakes:
  • Using dot notation for hash keys
  • Multiplying prices instead of summing
  • Starting sum at 1 instead of 0

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Ruby Quizzes