From: matt@... (matt neuburg) Date: 2008-12-01T03:54:43+09:00 Subject: Re: Help me understand how this block works? Brian A. wrote: > Here is the line: > roman_string.to_s.upcase.split(//).reverse.inject(0) do |memo, digit| > > If roman_string contains the value "IV", when we come to this line can > you please explain what the 'inject' does? When I step through it in > debug mode, I can see it gets assigned '0'. But how is the 'digit' > populated? How does it know it gets the 'V' first and subsequently 'I'? > Does it do this by default because the inject(0) populates the memo so > the only variable left is digit? 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. -- matt neuburg, phd = matt@tidbits.com, http://www.tidbits.com/matt/ Leopard - http://www.takecontrolbooks.com/leopard-customizing.html AppleScript - http://www.amazon.com/gp/product/0596102119 Read TidBITS! It's free and smart. http://www.tidbits.com