From: Alan Chen Date: 2002-11-19T02:42:29+09:00 Subject: Re: Explanations of yield for a newbie? On Tue, Nov 19, 2002 at 12:52:25AM +0900, christopher.j.meisenzahl@citicorp.com wrote: > > I've been reading the pickaxe book and I think I kind of understand them, but I > really need a concise explanation of the point of them and the power of them to > put me over the top. > > Any references to more info on this very much appreciated! > > I think one of the points of yield is to allow user defined classes to have > easily defined iterators? Think of a block as an anonymous subroutine. Instead of saying def func(x,y) # ... do stuff end it goes { |x,y| # ... do stuff } yield is just the way you call the block passed to the function. If you have a C/C++ background, it might help to think of blocks as function pointers and yield as dereferencing a function pointer. Yield is similiar to a callback function. Even closer to function pointers in C/C++ is a proc object. myproc = proc { |x,y| puts "x: #{x}, y #{y}" } # You can accept these objects as parameters to functions def func(x,y,p) p.call(x,y) end func(1,2,myproc) Using yield is just a more convenient way to perform the same thing. The yield version of the above might go as follows: def func(x,y) if( block_given?) yield(x,y) end end func(1,2) { |x,y| puts "x: #{x}, y #{y}" } -- Alan Chen Digikata Computing http://digikata.com