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
Passing parameters allows you to call the same code block, but with different input. For example<ref>http://www.tutorialspoint.com/ruby/ruby_blocks.htm</ref>:
def test yield 5 puts "You are in the method test" yield 100 end test {|i| puts "You are in the block #{i}"}
Executing this code results in:
You are in the block 5 You are in the method test You are in the block 100
See how the same code block results in different output yielded to the first and second times? That's because the values 5
and 10
are passed each time, respectively, and output by the code block.
Why It's Useful
Examples
Further Readings
References
<references/>