From: Gary Wright Date: 2009-12-15T11:32:47+09:00 Subject: Re: Newbie Question: Blocks and Parameters On Dec 14, 2009, at 8:15 PM, Derek Michael wrote: > > Now what gets me confused is once I get to these following examples: > > class MyClass > def command1() > yield(Time.now) > end > end > > m = MyClass.new > m.command1() {|x| puts "Current time is #{x}"} > > In the above example, how does 'x' get the Time.now value? In the first > code I have above, 'x' becomes the actual integer object (1, 2, and 3). > So in this case, how does the 'x' variable in this block code get the > Time.now value when executed through yield? Your definition of command1 depends on an implicit rather than explicit block parameter. The implicit block parameter is called by the yield keyword. An alternative definition of command1 that uses an explicit block parameter would be: class MyClass def command1(&block) block.call(Time.now) end end There is a small penalty for using an explicit block parameter as the implicit block must be wrapped up in a Proc object and bound to the formal parameter rather remaining implicit. The implicit form is most often used when the block is invoked during the execution of the method whereas the explicit form is more common when the block is going to be stored to be called at some later time (such as with callbacks). Gary Wright