0
0
Rubyprogramming~15 mins

Reduce/inject for accumulation in Ruby - Mini Project: Build & Apply

Choose your learning style9 modes available
Sum of Prices Using Reduce/Inject
📖 Scenario: You are managing a small store's inventory. Each product has a price, and you want to find out the total value of all products combined.
🎯 Goal: Build a Ruby program that uses inject to calculate the total price of all products in a dictionary.
📋 What You'll Learn
Create a hash called products with exact product-price pairs
Create a variable called total_price to hold the sum
Use inject on products.values to calculate the total
Print the total_price value
💡 Why This Matters
🌍 Real World
Calculating totals is common in shopping carts, budgets, and reports where you add many numbers together.
💼 Career
Knowing how to use <code>inject</code> helps you write clean and efficient Ruby code for data processing tasks.
Progress0 / 4 steps
1
Create the products hash
Create a hash called products with these exact entries: 'apple' => 100, 'banana' => 50, 'orange' => 75
Ruby
Need a hint?

Use curly braces {} to create a hash with keys and values separated by =>.

2
Create the total_price variable
Create a variable called total_price and set it to 0
Ruby
Need a hint?

Just write total_price = 0 to start your sum at zero.

3
Use inject to sum the prices
Use inject on products.values to add all prices and assign the result to total_price
Ruby
Need a hint?

Use inject(0) { |sum, price| sum + price } to add all values starting from zero.

4
Print the total price
Write puts total_price to display the total price
Ruby
Need a hint?

Use puts total_price to print the number on the screen.