Ruby Inject and Ruby Reduce

Ruby Inject and Ruby Reduce
In: Ruby

I've heard about inject for the first time when I started to work with Ruby after about 5 years of coding in JavaScript, Python and Java. It turned out that inject is just a fancy name for the reduce() function (many rubyists prefer inject though, so that reduce is just a fancy name for inject to them).

Just in case you wonder, "Why do I have to stuff my brain with multiple names for the exact same method?"... Because we can!

Why is it called inject?

You could think of it as elements from a collection being sent somewhere with an operation injected in between:

You could also view it as a collection of elements being injected into one whole:

Martin Fowler in his blog post on reduce, kind of indicates that inject comes from smalltalk, where it’s called inject:into:. I'm not sure about the exact Why, though. Just don't mix it up with "dependency injection" or the mathematical "injective function", they don't have much in common.

Why is it called reduce?

This one's pretty intuitive and also more known in the world of data (think MapReduce) and other languages (think Python, JS etc.). Basically, you have a collection of Something and you reduce this collection to one entity.


Ruby inject / reduce default values

I'm not sure if I have that from some other language from back in the old days, when I still happily used reduce, but one day I was banging my head for some time hunting a nasty "bug":

[1, 2, 3].inject { |sum_so_far, current_item| sum_so_far + current_item + 1 }
=> 8 # supposed to be 9 in my brain

Must be definitely a Ruby compiler bug! However, in nearly 100% of the cases, those are internal read-the-docs-brain-bugs. As you can see, there's no default value to start out when you don't provide an argument to inject. Instead, the first value to be operated on is the first element in the collection.

More from RichStone Input Output
Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to RichStone Input Output.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.