From: "Brian A." Date: 2008-12-01T04:13:47+09:00 Subject: Re: Help me understand how this block works? matt neuburg wrote: > > Just look at the docs: > > http://ruby-doc.org/core-1.8.7/classes/Enumerable.html > > Scroll down to "inject" and look at the third format. The "0" from the > original call is the first value passed to "memo"; meanwhile, the > elements of the array are the values passed each time to "digit". > > The "digit" population goes in the order "V" then "I" because the string > has been reversed with the "reverse" method. > > The hard part of "inject" to understand is not either of those; it is > the matter of the *subsequent* values of "memo". It is the result of > each previous execution of the block. (There is no "previous execution > of the block" the first time, obviously, so we need to settle on the > first value in some other way. Here, that way is the specification of > the "0" parameter.) > > The example in the docs is a very nice one: > > (5..10).inject(1) {|product, n| product * n } #=> 151200 > > If you can see why the final output of the block is the multiplicative > product of all the numbers in the enumerable, you've understood > "inject". The "memo" (here called "product") is seeded with "1" because > multiplying any value by "1" gives the same value, so we get the right > answer for the *first* enumerable and then we're off to the races. > > So, our "product" and "n" values each time thru the loop are: > > 1, 5 > 1*5, 6 > 1*5*6, 7 > 1*5*6*7, 8 > 1*5*6*7*8, 9 > 1*5*6*7*8*9, 10 > > Finally, the last time through, we produce 1*5*6*7*8*9*10 and stop. > > If you apply that kind of reasoning to your example, you'll understand > it! > > m. Thank you, that explains it very well for me. Another quick question. Would it be possible to inject to two different vars? For instance if something like (syntax is probably wrong if its even possible): (5..10).inject(1).inject(2) {|product, variable_two, n| product * variable_two * n} -- Posted via http://www.ruby-forum.com/.