Understanding Ruby's 'inject' Method
As I have been leveling up my Ruby skills and knowledge, I’ve discovered that there are many concepts that I still don’t have a strong grasp on. One example is the inject
instance method in the Enumerable module.
What I thought
I thought that inject
did something similar to collect
:
With collect
any block it is passed is executed on each element of the array, and a new array is returned with the updated values.
inject
behaves much differently. It starts with a value, and updates that value for each element of the array.
I found an awesome visualization of what inject
does, that will shed some light on what is really happening.
If the visualization isn’t enough, here is a deeper look at what is going on.
Using inject
is helpful when you find yourself doing what I just demonstrated: starting with some empty value, changing that value in a loop, and returning it afterwards.