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 you are passing it, just as you did in the first example in this chapter. That method receives the block without having to declare a named parameter for it, and it calls the block with yield.

Here is a slightly more useful example:

def caps( anarg )
    yield( anarg )
end

caps( "a lowercase string" ){ |x| x.capitalize! ; puts( x ) }

Here the caps method receives one argument, anarg, and passes this argument to a nameless block, which is then executed by yield. When I call the caps method, I pass it a string argument ("a lowercase string") using the normal parameter-passing syntax. The nameless block is passed after the end of the parameter list.

When the caps method calls yield( anarg ), then the string argument is passed into the block; it is assigned to the block variable x. This capitalizes it and displays it with puts( s ), which shows that the initial letter has been capitalized: “A lowercase string.”

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.137.12