From: 7stud -- Date: 2007-09-24T13:52:25+09:00 Subject: Re: how to add an iterator to a class? Here's a super simple example of an iterator: def test yield yield yield puts "all done in test" end test {puts "hello"; sleep(2)} In that example, test() calls the block but does not send it any arguments--just like you can call a method and not send it any arguments. Note that the block is not defined to accept any arguments. When the first yield statement is encountered, the block is called. How does the yield statement know what block to call? yield calls the block specified to the right of the test method call. What if you call test and don't specify a block? r4test.rb:2:in `test': no block given (LocalJumpError) from r4test.rb:9 After the first yield statement in test is encountered, execution halts at the point of the first yield statement until the block outputs "hello" and finishes sleeping. Then execution continues in test. The next line in test is another yield statement, so the block is called again, and execution halts in test until the block finishes. The same thing happens a third time. Finally, test outputs its terminating message. Blocks can also return values to a yield statement--just like a method can return a value to a method call, e.g. def get_calc 10 * 2 end def do_homework answer = get_calc #return value replaces the method call in the code puts answer end do_homework Here is how a block returns a value to a yield statement: def test result = yield 10 #catch the value returned by the block in a variable puts result end test {10 * 2} -- Posted via http://www.ruby-forum.com/.