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
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:
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 of
Have you ever used
yield to do something clever or noteworthy? Sound off in the comments!
Make yourself useful.