What's the Difference Between "reduce" and "inject" Methods in Ruby?

In Ruby, the Enumerable#reduce method is an alias for the Enumerable#inject method. Therefore, they have no differences. This can be seen, for example, in the following examples (which are equivalent):

numbers = [1, 2, 3, 4, 5]
total = numbers.inject(0) { | sum, n | sum + n }

print total #=> 15
numbers = [1, 2, 3, 4, 5]
total = numbers.reduce(0) { | sum, n | sum + n }

print total #=> 15

Also, there is no performance benefit to using either one over the other, and you may use them interchangeably.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.