Monday, March 29, 2010

External iterator for Ruby 1.9

Until Ruby 1.8, there was only internal iterator. But from Ruby 1.9, external iterator comes.

external_iterator.rb
array_1 = %w{1 2 3 4 5 6 7 8 9}
array_2 = %w{a b c d e f g h i}

external_iterator_1 = array_1.each
external_iterator_2 = array_2.each

begin
  while (element_1 = external_iterator_1.next) and
    (element_2 = external_iterator_2.next)
    puts "#{element_1} #{element_2}"
  end
rescue StopIteration
  puts 'External iterator has finished'
end
Let's check!
> ruby external_iterator.rb
1 a
2 b
3 c
4 d
5 e
6 f
7 g
8 h
9 i
External iterator has finished

No comments:

Post a Comment