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.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.