July 2011
Intermediate to advanced
400 pages
8h 46m
English
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
endIt 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 ...
Read now
Unlock full access