Ruby - Returning Blocks from Methods


You could create a block inside a method and return that block to the calling code.

You can create multiple blocks from the same block template and each instance of which is initialized with different data.

Here, the code created two blocks and assigned them to the variables salesTax and vat, each of which calculates results based on different values (0.10) and (0.175):


def calcTax( taxRate )
    return lambda{
        |subtotal|# from  w ww  .j  av a2 s  .c o m
            subtotal * taxRate

salesTax = calcTax( 0.10 )
vat = calcTax( 0.175 )

print( "Tax due on book = ")
print( 10 ) )       #=> 1.0

print( "\n\n")

print( "Vat due on DVD = ")
print( 10 ) )            #=> 1.75


Related Topic