0
0
Rubyprogramming~3 mins

Why Reduce/inject for accumulation in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could replace long loops with a single, powerful command that does all the work for you?

The Scenario

Imagine you have a list of numbers and you want to find their total sum or multiply them all together. Doing this by hand means writing a loop that adds or multiplies each number one by one.

The Problem

Writing loops manually can be slow and easy to mess up. You might forget to update the total, or accidentally overwrite values. It also makes your code longer and harder to read.

The Solution

Using reduce (also called inject in Ruby) lets you combine all items in a list into one value with a simple, clear command. It handles the looping and accumulation for you, making your code neat and less error-prone.

Before vs After
Before
total = 0
numbers.each do |n|
  total += n
end
puts total
After
total = numbers.reduce(0) { |sum, n| sum + n }
puts total
What It Enables

You can quickly and safely combine many values into one result with just one line of code.

Real Life Example

Calculating the total price of items in a shopping cart by adding each item's cost without writing long loops.

Key Takeaways

Manual loops are slow and error-prone.

Reduce/inject simplifies accumulation tasks.

Code becomes shorter, clearer, and safer.