Array Iterators

It's easy to create an array iterator with a loop:



class Array
  def iter
    for i in 0...size
      yield self[i]
    end
  end
end

puts 'Calling a.iter'
array.iter { |element| puts element }
puts 'Done.'

It's almost as easy to do the same thing with recursion:



class Array
  def recur(i = 0, &body)
    if i < self.size
      yield self[i]
      recur(i + 1, &body) # &body used as actual parameter
    else
      nil
    end
  end
end

puts 'Calling a.recur'
array.recur { |element| puts element }
puts 'Done.'
The actual point of this example is to show how a recursive method can use a block. The trick is to use the ampersand (&) notation for both a formal parameter and as an actual parameter in the recursive call.