0
0
RubyComparisonBeginner · 3 min read

Reduce vs Inject in Ruby: Key Differences and Usage

reduce and inject in Ruby are two names for the same method used to accumulate a value across elements of a collection. They work identically and can be used interchangeably to combine elements by applying a block or symbol.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of reduce and inject in Ruby.

Factorreduceinject
Method TypeEnumerable methodEnumerable method
FunctionalityAccumulates values by applying a block or symbolAccumulates values by applying a block or symbol
AliasAlias of injectAlias of reduce
Common UsageUsed to sum, multiply, or combine elementsUsed to sum, multiply, or combine elements
Syntaxcollection.reduce(initial) { |acc, elem| ... }collection.inject(initial) { |acc, elem| ... }
Introduced InRuby 1.8+Ruby 1.8+
⚖️

Key Differences

In Ruby, reduce and inject are actually the same method under different names. There is no functional difference between them; reduce is simply an alias for inject. This means they behave identically in all cases.

The choice between reduce and inject is mostly a matter of style or readability. Some developers prefer reduce because it clearly describes the process of reducing a collection to a single value. Others use inject because it is the original name in Ruby's Enumerable module.

Both methods take an optional initial value and a block that receives an accumulator and the current element. They apply the block repeatedly to combine elements into one result. You can also pass a symbol representing a method name (like :+) instead of a block for common operations.

⚖️

Code Comparison

Here is an example using reduce to sum numbers in an array.

ruby
numbers = [1, 2, 3, 4, 5]
sum = numbers.reduce(0) { |acc, num| acc + num }
puts sum
Output
15
↔️

inject Equivalent

The same sum operation using inject looks like this:

ruby
numbers = [1, 2, 3, 4, 5]
sum = numbers.inject(0) { |acc, num| acc + num }
puts sum
Output
15
🎯

When to Use Which

Choose reduce when you want your code to clearly express the idea of reducing a collection to a single value, which can improve readability for beginners. Choose inject if you are working in a codebase or team that prefers the traditional Ruby naming or if you want to match older Ruby documentation. Since they are identical, consistency within your project is more important than which one you pick.

Key Takeaways

reduce and inject are the same method with different names in Ruby.
Both methods accumulate a single value from a collection by applying a block or symbol.
Use reduce for clearer intent; use inject for traditional style.
They accept an optional initial value and work identically in all cases.
Consistency in your codebase is more important than choosing one over the other.