Sunday, March 18, 2007

Code block & keyword yield

Code block is a kind of construct, is an optional component of method call.

When you call a method—any method, any time, with or without arguments—you have the option of supplying a code block.

But why would you add a block of code to a method call? You’d do it so that your method can yield:
If you provide a code block when you call a method, then inside the method, you can yield control to that code block to execute the code in the block, and return control to the method body right after the call to yield.

Like a method, a code block can take arguments:
Methods do this with parenthetical lists of variable names for the arguments:
def one_method (a,b,c)
end
Code blocks have a different syntax; instead of parentheses, they use a pair of pipes (I I):
one_code_block do I a, b, c I
end

我觉得这yield没啥意思。如果需要半路这样的话,我调用另一个method不就行了。

No comments: