From: Dave Burt Date: 2006-05-21T12:06:32+09:00 Subject: Re: rubynuby - confused by method name "inject" Jeff Pritchard wrote: > Can anybody explain to me how the Enumberable#inject method is > "injecting" something into something? I find it very difficult remember > method names when I don't "get" them. So far in Ruby, "inject" takes > the cake for least understandable method name (with my own particular > convoluted gray matter). > > Can somebody give some examples of its use and state in words how it is > "injecting" something into something? ["foo", "bar"].inject(5) {|total, word| total + word.length } #=> 11 This example injects the result of the block applied to each element of the collection into a single value. I actually prefer the Haskell term, "fold" -- it repeatedly folds the function of the value and an element of the collection back into the value. > If anybody wants to take a stab at "collect", that would be welcome > also. I use "map", which is an alias of "collect". ys = xs.map {|x| x * x } It takes a block (a mapping from X to Y) and applies it to a collection of Xs to map them to Ys. Cheers, Dave