Project Ramon

A learning journey from a Ruby noob perspective

Building with Ruby Blocks

koans3_header_img

 

From the Ruby Learning site:

A Ruby block is a way of grouping statements, and may appear only in the source adjacent to a method call; the block is written starting on the same line as the method call’s last parameter (or the closing parenthesis of the parameter list). The code in the block is not executed at the time it is encountered. Instead, Ruby remembers the context in which the block appears (the local variables, the current object, and so on) and then enters the method.

Any code surrounded by curly braces { } or do..end are considered blocks. We can think of code between either { } or do..end as being put together as a single unit, that gets passed into a method for its usage.

Heres an illustration of how a normal method call works versus one executing a block:

The method office_tool doesn’t return the block in the above illustration, although we wrote a block for this method, we have yet to call it with the yield statement. yield invokes the block without any object references needing to be involved. Blocks can be passed to methods without any parameters using the same yield statement.

Check out an example:

PS. You won’t get any complaints from me by calling out my team selection, I’m just a guy with a dream.

Now that we have some components of blocks introduced lets see some neat ways to take this yield statement out for a spin.

Above, we defined a method called blt_components which has five yield statements, each contains one recipe component for a BLT sandwich.

Next we created an array named blt_sandwich that represents an assembled entree and pass a block to the blt_components method. Inside the block, we’re just appending << each yield parameter into our blt_sandwich array. Think of this as making the sandwich. Finally we call the blt_sandwich variable which returns the array with its complete list of ingredients.

There are more to Ruby blocks, Ruby Koans

Advertisements

Categories: AirPair, Newbie, Ruby

Tags: , ,

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