Ruby - Extend Array class to add your own iterator method

Description

Extend Array class to add your own iterator method

Demo

class MyArray < Array
    def initialize( anArray )
        super( anArray )#  w w  w.  j av a 2s .c o  m
    end

    def timesRepeat( aNum )
        aNum.times{                 # start block 1...
             | num |
             self.each{             # start block 2...
                  | anitem |
                  yield( "[#{num}] :: '#{anitem}'" )
             }                      # ...end block 2
        }                           # ...end block 1
    end
end

numarr = MyArray.new( [1,2,3] )
numarr.timesRepeat( 2  ){ |x| puts(x) }

Result

Related Topic