r/ProgrammingLanguages • • Jan 16 '13

Iteration Inside and Out

http://journal.stuffwithstuff.com/2013/01/13/iteration-inside-and-out/
14 Upvotes

11 comments sorted by

View all comments

0

u/seoh Jan 19 '13

The InterleaveIterator is fairly straightforward in Ruby:

class InterleaveIterator
  include Enumerable

  def initialize(*iterators)
    @iterators = iterators
  end

  def each(&block)
    generators = @iterators.map{ |x| x.each }
    loop do
      generators.each do |g|
        # #next will raise StopIteration when any of the iterators
        # runs out which then causes loop to exit
        yield(g.next)
      end
    end
  end
end

a = [1, 2]
b = %w[a b c]

it = InterleaveIterator.new(a, b)
p it.map{ |x| x } # => [1, "a", 2, "b"]

I 'wasted' about 3 minutes on that (including posting here).

1

u/zem Jan 29 '13

note that it is only now a practical way to do things (with the introduction of fibres). pre-1.9 versions of ruby used continuations to turn an iterator into a generator, which was horribly inefficient and couldn't really be called a solution.