Mapping two (or more) arrays in parallel

Fearless Fool wrote in post #1048783:

Neither of these feel especially right: the first case needs to zip
together two arrays, the latter just seems clunky. Is there an elegant
form that you like to use in this case, perhaps by writing a special
iterator?

I always thought it would be cool if map, select, zip etc. with a block
returned an Enumerator rather than an Array. Then if you want an array
you could add .to_a, but if you didn't, you could process the results as
they are generated.

Something like this (untested)

module Enumerable
  def lazy_zip(*others)
    Enumerator.new do |y|
      each_with_index do |item, index|
        y << ([item] + others.map { |o| o[index] })
      end
    end
  end
end

a = [1,2,3]
b = [4,5,6]
c = [7,8]

a.lazy_zip(b,c) { |row| p row }

Instead of generating a huge result array up-front, the elements are
yielded one at a time.

ยทยทยท

--
Posted via http://www.ruby-forum.com/\.