Working with Ruby Blocks

April 8, 2009

Today’s topic deals with blocks in ruby. So the first question that you might ask is what is a block.
I will fall back to my C# experience in order to try and explain what a block is.
A block is a piece of code that you want to execute within a context of another piece of code.
I will use a string Array as an example in C# to show you what I mean. The code below creates a new instance of an array that is populated with 3 different names. I then use what is called an Action to loop through each string in the array and write the name to the console.
Here is what the code looks like.

public void DisplayNames()
{
string[] names =
new string[] {"Bob", "John", "Sam"};
Array.ForEach(names,
name => Console.WriteLine(name));
}

and here is what the Ruby code looks like:

def DisplayNames
  names = %w( Bob John Sam )
  names.each do |name|
    puts name
  end
end

The basic idea behind using blocks is that you want to perform some sort of a generic action that can be used throughout your application but you don’t want to duplicate the same code all over. In this case you can use blocks to perform this action of looping through your array and just specifying what should happen to each item.

The basic implementation of the ruby each function looks like this:

def print_values(list)
    for item in list
        yield(item)
    end
end

One interesting thing that I would like to point out is that there are different ways to pass a block to the method.

names = %w( Bob John Sam )
print_values(names) { |name| puts name }

or

names = %w( Bob John Sam )
print_values(names) do |name|
    puts name
end

What you see here is that we are creating an array of values and then we are passing that array to the print_values method which will perform the iteration logic over the array and will call the block after the print_values(names) call in order to perform what ever the logic in that block is. The yield keyword is what enables the call to the given block of code and it passes the variable that we are currently iterating over.

Advertisements

One Response to “Working with Ruby Blocks”

  1. iLya Lozovyy Says:

    Rachel,
    Thanks for contacting me however I am not seeking employment at the moment but I will let you know if I ran across anyone who is interested.
    Regards,

    iLya Lozovyy


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Advertisements
%d bloggers like this: