For some reason, some people who hang out on ruby-talk seem to have a compulsion to periodically opine that
“inject() is always the inefficient solution possible.”
I think that this statement, even if it were true, which I’m pretty sure it isn’t, being a claim for universality,
isn’t particularly good advice.
My buddy Kent Beck has generated quite a few memes in the software development community.
One of the more well known is “Make it run. Make it right, Make it fast.”
Although the roots of this advice can be traced back to Butler Lampson.
This is advice that anyone who wants to be a software craftsman needs to take to heart.
The order is important.
First you make sure that the code runs, then you need to make it right.
Making it right doesn’t mean that it does the right thing,
that’s a large part of making it run,
it mean’s making the code clear and maintainable, either by a future you, or by someone else.
Only then you should make it fast, without unnecessarily affecting your success in keeping it right.
And the best way to make it fast is to slavishly follow the
3 rules of optimization
While there are some who just seem to hate inject, it can, as you point out, be much more intention revealing,
which helps in making the code right.
In Ruby 1.9, the inject method also has the alias reduce, which is even clearer in the cases where there’s no
initial value to inject into the enumeration. More languages use reduce for this case, and don’t provide an argument
for the initial value at all. Ruby got the name inject from Smalltalk’s inject: aValue into: aBlock collection method
where Smalltalk’s keyword message selector syntax does a better job of revealing the meaning of the parameters.
Now, that’s not to say that inject/reduce should be overused, the key tension is whether or not it is actually intention revealing, or
overly clever, or even stupid.
I confessed here some time ago, that I can be just as guilty as anyone of being
cleverly stupid.
But I don’t recommend it.
This is just one of those things, like when and when not to use optional parentheses in Ruby,
which really need a bit of thoughtful reflection, rather than blind adherence to convention.