After a time of much outer influence and inner struggle, I, a self-proclaimed Microsoft fanboy, decided to abandon everything I’ve known for the last 6 years as a .NET developer and sample the sweet simplicity and sheer power that is Ruby on Rails.
One of the first things I learned while working on my first Rails project was the use of Ruby’s yield statement. Coming from C#, I expected the yield statement to act a bit differently than it does in Ruby. Basically, the yield statement is provided as a way to ease the creation of iterators. It gives control to a user-specified block from within a method’s body.
An example of this is:
1 2 3 4 5 6 7 8 | #!/usr/bin/ruby def where_am_i puts "You are in the method" yield puts "You are in the method again" yield end where_am_i { puts "You are in the block" } |
This will produce the following:
You are in the block
You are in the method again
You are in the block
You can pass parameters with the yield statement as well:
1 2 3 4 5 6 7 8 9 10 | #/usr/bin/ruby def my_name_is puts "Hi, my name is..." yield "Who?" puts "Hi, my name is..." yield "What?" puts "Hi, my name is..." yield "Slim Shady!" end my_name_is { |s| puts "#{s}" } |
This will produce the following:
Who?
Hi, my name is…
What?
Hi, my name is…
Slim Shady!
As you can see, the yield statement is written followed by the parameter(s) being passed. Yes…you can pass multiple parameters! Check out the next example:
1 2 3 4 5 6 | #/usr/bin/ruby def i_have_twin_daughters puts "I have twin daughters" yield "Ruby", "Perl" end i_have_twin_daughters { |a, b| puts "Their names are #{a} and #{b}" } |
This will produce the following result:
Their names are Ruby and Perl




Justin welcome to the Ruby Lens Colored life my friend! :-)
Comment by jaredd — April 9, 2009 @ 3:22 pm