Ruby Block passing Syntax
Ruby is one of many languages that allow lexical closures, otherwise known (kind of ) as anonymous functions or blocks. These functions are dynamically created. The function can take the form of a defined function. For example:
Or, you could define it as follows:
Or, you could define it this way:
Now, anonymous functions or blocks can be passed to other functions as parameters. A function that takes a function (defined or anonymous) as a parameter will optionally execute the function in its program flow. Suppose there is a function called printit() defined as follows:
Now, suppose you want to print each element of a range. You will call each on the array, which will run the block passed to each for each element of the array.
You could also pass an actual block of code to run. The block is surrounded by do and end or { and }. Objects between the vertical bars are optionally passed to the block (depending on the definition of the block), and they are used by the block to execute. The return value of a block is the value of the last expression in the block.
You will get the same output as earlier. Ditto for the following:
In Ruby, map, reduce, and select all take a code block as a parameter, and the code block is executed as defined by the function
comments powered by Disqus