Explanations of yield for a newbie?

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?

Thanks in advance and have a good day!
Christopher

Christopher J. Meisenzahl CPS, CSTE
Senior Software Testing Consultant
Spherion
christopher.j.meisenzahl@citicorp.com

Mmm… I’m not sure that I’d actually define it that way. yield
calls a block associated with the method. File.open uses an optional
block to open and close a file while the logic is executed inside of
the block. FXRuby buttons can have blocks associated with them as
“responders” to actions on those buttons.

Iterators use blocks to do something with each element (or index) as
it is being iterated over.

-austin
– Austin Ziegler, austin@halostatue.ca on 2002.11.18 at 12.06.51

···

On Tue, 19 Nov 2002 00:52:25 +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}”
}

···

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?


Alan Chen
Digikata Computing
http://digikata.com