Ruby - Using yield to run a block

Description

Using yield to run a block

Demo

def caps( arg )
    yield( arg )# from w w  w  .ja  v a  2  s . c  om
end

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

Result

Here the caps method receives one argument, arg, and passes this argument to a nameless block, which is then executed by yield.

When calling the caps method, the code passes 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( arg ), then the string argument is passed into the block.

Related Topic