Learning To Code

Join me as I take the plunge!

It's Reduce, Not Inject

When I think of the term ‘inject’, I think of Ron Popeil’s Solid Flavor Injector - where you can literally put solid garlic cloves INTO a meat roast. Classy.

When I first came across Ruby’s method ‘Inject’ I was very confused. The point of inject is to get rid of local variables that iterate when you want to do something simple like sum up the first 10 numbers.

(1..10).inject(0) { |result, element| result + element }

But what this ‘Inject’ method is really doing is reducing. Reducing a range of 10 numbers into just their one sum.┬áReducing the number of local variables you need to keep track of.┬áReducing the amount of code you need to write. This is why, even after I learned about inject, the name was still throwing me off. Then I discovered that ‘Reduce’ is actually an alias to ‘Inject’ in ruby! Thank you Matz for making me happy. I’ll be leaving the notion of injecting to Ron Popeil, and will write reduce methods in my code from now on.