From: dblack@... Date: 2006-05-21T11:56:46+09:00 Subject: Re: rubynuby - confused by method name "inject" Hi -- On Sun, 21 May 2006, 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? > > thanks, > jp > > P.S. > If anybody wants to take a stab at "collect", that would be welcome > also. I have just about the mental energy for collect right now, so I'll give that a try :-) The basic usage (just to have an example): You have an array: [1,2,3,4,5] You call: new_array = array.collect {|element| element * 10 } The result (new_array) is: [10,20,30,40,50] Now, in terms of the word "collect" itself: Imagine that the elements of the first array are sitting on a bus. The conductor comes through the bus and *collects* the fare from each element. The fare is: yourself times 10. The cumulative result is a new array, consisting of the old array's elements but each multiplied by 10. So collect is an iterative process, where a new value is "collected" from each old value, courtesy of being passed to the code block. The new array is thus a one-to-one mapping of the old array, with the values transformed. (So collect is also called "map" :-) David -- David A. Black (dblack@wobblini.net) * Ruby Power and Light, LLC (http://www.rubypowerandlight.com) > Ruby and Rails consultancy and training * Author of "Ruby for Rails" from Manning Publications! > http://www.manning.com/black