Since this old discussion is one of the top ranking pages when you
Google ‘ruby inject’ or ‘inject method’, it’s probably worth adding that
since version 1.8.7 Ruby has had the #reduce method, which is an alias
of #inject.
It seems a lot of people prefer #reduce, because it’s reducing the list
down to a single value. Personally I think it’s just as bad. Another
commenter said, the classic example of #inject is to sum the elements of
an array. So now we have a method called ‘reduce’ to add elements
together?! One might expect #reduce to work more like #drop or #take or
#select–to create a smaller (reduced) subset. To me it communicates
nothing of the combining nature of the method–unless maybe I think of
it in cooking terms, where one boils a sauce to condense it, but that’s
being generous I think.
It’s hard to come up with a good short name for such a versatile
function without implying an increase or decrease of successive results.
I think of the word ‘cumulative’ when I think of how #inject is using
the result of one iteration in the next one, and ‘cumulate’ is a verb,
but perhaps not a very common one, and it does kind of imply an increase
in successive results. ‘Accumulate’ is similar.
I wouldn’t mind Jeff’s suggestion of ‘combine’, except I think it could
very easily be confused with concatenation methods like #concat and #+,
which combines two arrays into one.
But then we have ‘fold’, which is the name Wikipedia went with in
categorising these types of functions. Why on earth couldn’t Ruby have
gone with this? Like ‘reduce’, it’s used by a stack of other languages,
but unlike ‘reduce’ it doesn’t imply a decrease in value. Check out the
top definitions of the word ‘fold’ from my dictionary:
fold
verb [ with obj. ]
1 bend (something flexible and relatively flat) over on itself so that
one part of it covers another: Sam folded up the map.
• (fold something in/into) mix an ingredient gently with (another
ingredient), especially by lifting a mixture with a spoon so as to
enclose it without stirring or beating: fold the egg whites into the
chocolate mixture.
So there’s that cooking metaphor again. But how elegant is that! No
metaphor is going to be a perfect fit for all that #inject is able to
do, but I reckon #fold would be a thousand times better than #inject and
#reduce.
I’m hoping they’ll add #fold as an alias method one day. But until then,
I guess I’ll stick with #inject.