Blocks are pieces of code that can be added onto the outside of a function call. Inside the function it can 'yield' which passes control and values to the block.

They are mainly used for certain types of loops and iteration. For example to add up the numbers from 0 to 10 (exclusively)...

sum = 0
10.times() do |i|
    sum = sum + i

The block is everything from the 'do' to the 'end', and the block is being placed on the 'times()' method call. You can use the 'do' and 'end' keywords, or you can use braces...

sum = 0
10.times() { |i| sum = sum + i }

By convention you use braces for single line blocks and do-end for multi-line blocks (however you can use either for both multi-line and single-line blocks).

The variables between the bars (the |i| bit) are the parameters for the block where values being passed in will be stored.

Another example adding up the sum of an array...

nums = [ 3, 9, 2, 0, -3, 98, 4 ]
sum = 0
nums.each() { |num| sum = sum + num }

Block Parameters

Blocks can be caught as a parameter of a function using the ampersand.

def f( &block )
    myBlock = block

f() do 
    // some code

The block parameter must be the last parameter, and only 1 is allowed.

If a block is attached to the function then it is held in the block parameter. If it is missing then the block parameter is null. Yielding will automatically call the block.

def f()
    yield 500

f() do |n|
    // outputs 500
    console( n )

Block parameters are instances of the Function class, so you can also call it manually using the 'call' method:

def f( &block )
    yield 5
    args = [ 10 ] args )

f() do |n|
    // First run using the 'yield' with n equal to 5,
    // and then again, using the 'call', where n is equal to 10.

This allows you to catch blocks and then call them later. Using this you can then use blocks as events.

button = new Button()
button.onClick() do

The 'onEachFrame' function is an example of a function that stores the block to be executed later.

However you can also use Anonymous Functions for creating Function objects.

See also

Functions - Function Class