From: "Jesús Gabriel y Galán" Date: 2009-12-15T18:41:28+09:00 Subject: Re: Newbie Question: Blocks and Parameters On Tue, Dec 15, 2009 at 8:29 AM, Derek Michael wrote: > Walton Hoops wrote: >> >> Going back to your first example.  A possible implementation of .each >> >> class Array >>   def each >>     x=0 >>     while x>       yield(self[x]) >>       x+=1 >>     end >>   end >> end >> >> Thus, in this example calling each calls yield passing in one at a time >> each member of the array.  Thus your block gets excuted once for each >> member of the array.  Does that help? I'm not sure how to explain it >> better. > > Thanks to the both of you for the explanations.  I think I understand > now.  I assume you mentioned the 'possible' implementation of .each > method to imply to me that the each method must have a yield in it since > it does something when you pass a block/closure, yes? Correct. The each method (which in MRI is probably implemented in C) yields values to the block. Walton provided a possible implementation in Ruby of the each method to show you the possible internal logic of each: go through the elements of the array and yield them to the block one at a time. In Ruby all methods can receive a block. They can use it without having to "declare" it if you use the yield keyword. If you want to explicitly refer to it, you need to "declare" it in the argument list, as Gary showed: def m(arg1, arg2, &blk) # do something with blk end As Gary said, you usually use the explicit version when you want to store the block for later use, and use yield in the other cases. For example: class Callback def initialize &blk @callback = blk end def random n = rand(100) @callback.call(n) end end irb(main):033:0> c = Callback.new {|rnd| puts "a random number is #{rnd}"} => #> irb(main):034:0> c.random a random number is 26 => nil irb(main):035:0> c.random a random number is 73 => nil Calling the random method will use the block provided when constructing the object as a callback. Jesus.