A. products.inject { |total, product| total + product.name }
B. products.inject(1) { |total, product| total * product[:price] }
C. products.inject(0) { |total, product| total + product[:price] }
D. products.inject(0) { |total, product| total + product.price }
Solution
Step 1: Access the price key correctly
Each product is a hash, so access price with product[:price].
Step 2: Sum prices starting at 0
Start with 0 and add each price to get total price.
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.
Final Answer:
products.inject(0) { |total, product| total + product[:price] } -> Option C
Quick Check:
Sum prices with inject and hash keys = B [OK]
Hint: 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
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.