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 ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.