Cover by Huw Collingbourne

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required