From: Simon Strandgaard Date: 2004-04-12T22:49:14+09:00 Subject: Re: zip block oddities/bug? On Mon, 12 Apr 2004 07:42:35 +0100, daz wrote: [snip] > Since an array is deliberately *not* being built, what > could usefully be returned outside the block ? > ("nil" seems like a good choice). > zip should simply just concatenate the data it gets back from the block. I have made a pseudo-implementation, where blocks is working. It differs sligthly from the real zip, because I am cheating and using the :[], rather than each. server> ruby a.rb [["a"], ["b"], ["c"]] [["a", 1, 3, 1], ["b", 2, 4, 1], ["c", nil, 5, 1], ["d", nil, 6, 0]] [[4, 1, "a"], [5, 1, "b"], [nil, 0, "c"]] [[0, :lo], [1, :lo], [2, :hi], [3, :hi], [4, :hi]] [9, "a", 8, "b", 7, "c"] server> expand -t2 a.rb module Enumerable def zip2(*args) res = [] self.each_with_index do |element, index| data = [element] + args.map{|i| i.respond_to?(:[]) ? i[index] : i} res += block_given? ? yield(data) : [data] end res end end p %w(a b c).zip2 p %w(a b c d).zip2([1, 2], [3, 4, 5, 6], 7) p %w(a b c).zip2(3, [4, 5]) {|i| [i.reverse]} p (0..4).zip2 {|i| [i << (i[0] < 2 ? :lo : :hi)]} p %w(a b c).zip2([9, 8, 7]) {|i| i.reverse} server> It wakes memories of inject. -- Simon Strandgaard