Ruby - Function Nameless Functions

Introduction

A Ruby block may be regarded as a sort of nameless function or method.

A block is like a nameless function. Take this block as an example:

{ |i|
    puts( i )
}

If that were written as a normal Ruby method, it would look something like this:

def aMethod( i )
   puts( i )
end

To call that method three times and pass values from 0 to 2, you might write this:

for i in 0..2
   aMethod( i )
end

When you create a nameless method (a block), variables declared between upright bars such as |i| can be treated like the arguments to a named method. I will refer to these variables as block parameters.

For example:

3.times { |i|
    puts( i )
}

The times method of an integer passes values to a block from 0 to the specified integer value minus 1.

So, this:

3.times{ |i| }

is very much like this:

for i in 0..2
    aMethod( i )
end

The second example has to call a named method to process the value of i, whereas the first example uses the name-less method (block) to process i.

Related Topics