Nameless Functions

A Ruby block may be regarded as a sort of nameless function or method, and its most frequent use is to provide a means of iterating over items from a list or range of values. If you have never come across nameless functions, this may sound like gobbledygook. With luck, by the end of this chapter, things will have become a little clearer. Let’s look back at the simple example given earlier. I said 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 (that is, 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.

Look again at my earlier 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 chief difference is that the second example has to call a named method to process the value of i, whereas the first example uses the nameless method (the code between curly brackets) to process i.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.0.85