O'Reilly logo

The Book of Ruby by Huw Collingbourne

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Blocks as Iterators

As mentioned earlier, one of the primary uses of blocks in Ruby is to provide iterators to which a range or list of items can be passed. Many standard classes such as Integer and Array have methods that can supply items over which a block can iterate. For example:

3.times{ |i| puts( i ) }
[1,2,3].each{|i| puts(i) }

You can, of course, create your own iterator methods to provide a series of values to a block. In the iterate1.rb program, I have defined a simple timesRepeat method that executes a block a specified number of times. This is similar to the times method of the Integer class except it begins at index 1 rather than at index 0 (here the variable i is displayed in order to demonstrate this):

iterate1.rb

def timesRepeat( aNum ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required