From: matz@... (Yukihiro Matsumoto) Date: 2002-11-15T06:12:26+09:00 Subject: Re: Array#next - Enumerable#next ? Hi, In message "Array#next - Enumerable#next ?" on 02/11/15, ahoward writes: |does anyone know a way to implement this generically for all enumerable |objects in an efficient manner? Scheme 1) Use "to_a" to convert Enumerable into Array first. Easiest way. Scheme 2) Use thread to save/restore "each" iteration. Scheme 3) Use continuation to save/restore "each" iteration. Hint, here's my "generator.rb" which uses scheme 3). You can start from this sample. matz. ------ class Generator def initialize(method, *args) @cont_l = nil method.call(*args) {|v| callcc {|c| @cont_i = c @value = v return unless @cont_l @cont_l.call } } @cont_i = nil @cont_l.call end def next unless @cont_i raise "no more element" end v = @value callcc{|cc| @cont_l = cc @cont_i.call } v end def more? if @cont_i then true else false end end end class Object def generator(method, *args) Generator.new(self.method(method), *args) end end if $0 == __FILE__ def zip(*args) generators = args.collect{|x| x.generator(:each)} ary = [] while generators.any?{|x| x.more?} ary.push(generators.collect{|x| x.next rescue nil}) end ary end a = 1..10 b = "a".."z" for x,y in zip(a,b) p [x,y] end end