From: "Jesús Gabriel y Galán" Date: 2009-12-19T07:46:04+09:00 Subject: Re: Newbie Question: Blocks and Parameters On Fri, Dec 18, 2009 at 11:19 PM, Derek Michael wrote: > Thanks guys.  I think I'm slowly wrapping my head around this. > > Now sort of in the lines of the callback you mentioned, I started > reading about the & operator and being able to convert blocks to procs > and vice versa. > > Here is an example of the code I was reviewing: > > puts "----Define a method which takes block as a Proc object argument" > def my_method(count, &my_block) >  value = 1 > >  # Execute the block "count" times while updating the vlaue i >  1.upto(count) do |i| >    value = value * i >    my_block.call(i, value) >  end > > end > > puts "----Invoke the method passing a code block" > my_method(5) {|i, result| puts "my_method(#{i}) = #{result} "} > > > So in this case, the variable 'i' gets the value of variable 'count' > assigned to it when executing the upto method which invokes a yield?  Am > I understanding this correctly?  It took me a while looking at that code > again, to understand where the 'i' was getting it's value... There are two 'i' in your code. The one inside my_method, which is the block param for the block passed to the upto method, will get each value from 1 to count in each iteration, because that is what upto yields to the block. The 'i' outside, the one which is a block param of the block passed to mymethod, will get the same value in each iteration, since you are calling it with the same 'i' that upto yields. So it will get 1,2,3,4 and 5. The example is a little bit contrived, if you are wrapping your head around yielding, blocks, etc. Try with simpler examples first: def my_method(&my_block) my_block.call(55) end my_method {|x| puts x} #=> 55 def my_method(&my_block) 1.upto(5) do |i| my_block.call(i) end end my_method {|number| puts number} #=> 1 2 3 4 5 BTW, the above are "equivalent" to this: def my_method yield 55 end and def my_method 1.upto(5) do |i| yield i end end which for this simple cases I prefer. I usually use the &blk form when I want to store the block for later use. Jesus.