From: Walton Hoops Date: 2009-12-15T11:07:38+09:00 Subject: Re: Newbie Question: Blocks and Parameters > -----Original Message----- > From: derekwrobel@gmail.com [mailto:derekwrobel@gmail.com] > Please have patience with my possibly basic basic question. I am > learning Ruby and studying blocks/closures right now and confused > without being able to find an answer. I was studying and first came > across this example > > [1,2,3].each {|x| puts "This is #{x}. "} > > > and this makes sense to me I believe. for each object (which is > integers 1, 2, 3), it runs the {} block code, passing in the integer > objects in as variable 'x', then puts out the string including the 'x' > variable. > > 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? You can pass any function a block, whether it will use it, or not. In order to execute the block passed to a function, that function must call yield. The arguments to yield get passed in as arguments to the block. Going back to your first example. A possible implementation of .each class Array def each x=0 while x