yield

Let’s see a few more blocks in use. The 4blocks.rb program introduces something new, namely, a way of executing a nameless block when it is passed to a method. This is done using the keyword yield. In the first example, I define this simple method:

4blocks.rb

def aMethod
    yield
end

It doesn’t really have any code of its own. Instead, it expects to receive a block, and the yield keyword causes the block to execute. This is how I pass a block to it:

aMethod{ puts( "Good morning" ) }

Notice that this time the block is not passed as a named argument. It would be an error to try to pass the block between parentheses, like this:

aMethod(  { puts( "Good morning" ) }  )     # This won't work!

Instead, you simply put the block right next to the method to which ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.