CSC/ECE 517 Fall 2012/ch1b 1w60 ac
SaaS - 3.8 yield()
Introduction (Preface)
Code Blocks & Closures
The Map & Grep Functions
The yield() Function
What Is It?
Simply put, the yield function in Ruby passes control to a user-defined code block. As simple as that statement is, it can be quite confusing, so here is a quick example<ref>http://www.tutorialspoint.com/ruby/ruby_blocks.htm</ref>:
def test
puts "You are in the method"
yield
puts "You are again back to the method"
yield
end
test {puts "You are in the block"}
Executing this code results in:
You are in the method You are in the block You are again back to the method You are in the block
First, take a look at the last line of code. You'll notice that the parameter to the test function is actually a code block. Next, look at where the text "You are in the block" appears: after the "You are in the method" text then again after the "You are again back to the method" text. Notice how this corresponds to where the yield statements are in the code? That's because the yield statement is calling the code block, then returning control to the test method.
Syntax
As you may have guessed from the previous example, the yield function's syntax is quite simple. In it's most basic form, the yield function can be called with:
yield
In this form, the yield function will simply execute the code block passed to the function it's called from. You can also pass parameters to the yield function which passes those parameters to the code block, like so:
yield parameter
How It Works
Why It's Useful
Examples
Further Readings
References
<references/>