Ruby - Returning Blocks from Methods

Introduction

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):

Demo

def calcTax( taxRate )
    return lambda{
        |subtotal|# from   w ww. j  a  va  2 s  .c om
            subtotal * taxRate
    }
end

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

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

print( "\n\n")

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

Result

Related Topic