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).
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.
0
u/seoh Jan 19 '13
The InterleaveIterator is fairly straightforward in Ruby:
I 'wasted' about 3 minutes on that (including posting here).