Unique Marketing, Guaranteed Results.

Yield to the Ruby Master

April 9th, 2009 by justin

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 method
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:

Hi, my name is…
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:

I have twin daughters
Their names are Ruby and Perl
  • Facebook
  • Google Bookmarks
  • email
  • NewsVine
  • Slashdot
  • Technorati
  • Yahoo! Buzz
  • BlinkList
  • Print
  • Propeller
Filed under: Programming — justin @ 2:37 pm on April 9, 2009

1 Comment

  1. Justin welcome to the Ruby Lens Colored life my friend! :-)

    Comment by jaredd — April 9, 2009 @ 3:22 pm

RSS feed for comments on this post. TrackBack URL

Leave a comment


Copyright © 2005-2011 PMA Media Group. All Rights Reserved