Ruby - Passing Named Proc Arguments

Introduction

When the last argument in a method's list of parameters is preceded by an ampersand (&), it is considered to be a Proc object.

You can pass an anonymous block to a procedure using the same syntax as when passing a block to an iterator.

The procedure itself can receive the block as a named argument.

Demo

def myMethod( a, b, c )
   a.call# from   w w  w . jav  a2  s.  c  o  m
   b.call
   c.call
   yield
end

a = lambda{ puts "one" }
b = lambda{ puts "two" }
c = proc{ puts "three" }
myMethod(a, b, c ){ puts "four" }

Result

The myMethod method executes the named block arguments using the call method and the unnamed block using the yield keyword.

myMethod2 method takes a single argument, &d.

The ampersand indicates that the &d parameter is a block.

Instead of using the yield keyword, the myMethod2 method is able to execute the block using the name of the argument:

Demo

def myMethod2( &d )
   d.call# from w w w. ja  v a  2s. c  o m
end
myMethod2{ puts "four" }

Result

A block argument with an ampersand is called in the same way as one without an ampersand.

To match an ampersand-argument, an unnamed block is passed by appending it to the method name.

myMethod3 method specifies a fourth formal block-typed argument (&d):

Demo

def myMethod3( a, b, c, &d)
    a.call# from  w  w w.ja v a2s.c o  m
    b.call
    c.call
    d.call        # first call block &d
    yield         # then yield block &d
end

a = lambda{ puts "one" }
b = lambda{ puts "two" }
c = proc{ puts "three" }

myMethod3(a, b, c){ puts "five" }

Result

This means the calling code must pass to this method three formal arguments plus a block, which may be nameless.

You can use a preceding ampersand in order to pass a named block to a method when the receiving method has no matching named argument.

Demo

def myMethod3( a, b, c, &d)
    a.call# from  w w  w .  jav a  2  s .  c o  m
    b.call
    c.call
    d.call        # first call block &d
    yield         # then yield block &d
end

a = lambda{ puts "one" }
b = lambda{ puts "two" }
c = proc{ puts "three" }

myproc = proc{ puts("my proc") }
myMethod3(a, b, c, &myproc )

Result

An ampersand block variable such as &myproc may be passed to a method even if that method does not declare a matching variable in its argument list.

This gives you the choice of passing either an unnamed block or a Proc object:

Related Topic