Yield! In the Name of Blocks

Flatiron School / 24 October 2013

The following is a guest post by Greg Eng and originally appeared on his blog. Greg is currently in the Ruby-003 class at The Flatiron School. You can follow him on Twitter here.

Let’s think it over

In an earlier post, I talked about a few Ruby iterators and how they abstract to become useful tools. As promised, I’m going to further break them down in order to describe the concept of yield in Ruby.

In Ruby, methods are functions that allow code to interact with all different pieces of the program. Compared to spoken languages, you can think of methods as the verbs which connect to nouns and other words to form sentences. Methods are able to receive a code block which unlocks limitless potential. When defining our own methods, the magic of yield comes into play. If a method expects a block, it can invoke it by using yield.

For example:

Here I am defining a weather class that takes an argument at instantiation. I’ve also defined a method forecast that will take any block given and pass it the argument.

As you can see, I’ve interpolated the variable with a friendly little forecast sentence.

But I could just as easily use a different block to perform a different function.

In this case… I am loudly saying it’s going to be fairly warm.

Building on this idea, you can see that it essentially allows any method to easily become an iterator. Here is another look at the iterators described in my previous post: eachcollectselect.

each dissected:

collect dissected:

select dissected:

BONUS none? dissected:

BONUS include? dissected:

These examples are simple and isolated, but yield truly provides myriad possibilities when building sophisticated programs. To prove it, check out this blog post by Michael Bleigh where he described constructing eloquent looking code to design a DSL (Domain Specific Language) with the help ofyield.

Have you ever used yield to do something clever or noteworthy? Sound off in the comments!

Ruby 'Exceptional' Knowledge- Previous Post Pies in the Sky Next Post