Ruby - Blocks as Iterators

Introduction

Many standard classes such as Integer and Array have methods that can supply items over which a block can iterate. For example:

Demo

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

Result

You can create your own iterator methods to provide a series of values to a block.

In the following code timesRepeat method executes a block a specified number of times.

Demo

def timesRepeat( aNum )
    for i in 1..aNum do
        yield i# from  w w w  .  j  a v a2s  . co  m
    end
end
timesRepeat( 3 ){  |i| puts("[#{i}] hello world") }

Result

The following code created a timesRepeat2 method to iterate over an array:

Demo

def timesRepeat2( aNum, anArray )
   anArray.each{ |anitem|#  w w  w . j  a v a2s . com
       yield( anitem )
   }
end
timesRepeat2( 3, ["hello","good day","how do you do"] ){ |x| puts(x) }

Result

Related Topic