Ruby - Using yield to run a block


Using yield to run a block


def caps( arg )
    yield( arg )# from  ww  w  . j  av a  2s  .c o  m

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


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