On Wed, 04 Aug 2004 00:28:12 +0900, Claus Spitzer wrote:
> That's a strong point. Elaborating a bit more on that, perhaps what is
> needed is not a new method (or a collection of them), but a way of piping
> objects instead of creating intermediate ones. Then methods could be still
> chained, but with better spatial efficiency.
>    -CWS

That's possible using the enumerator module.
The code would be then:

require 'enumerator'

a = [1, 2, 3]
b = [1, 3, 5]
a.to_enum(:zip, b).map{|x, y| x*y}
=> [1, 6, 15]

#the new map method:
class Array
   alias __map__ map
   def map(*args)
      enum = (args.empty? ? self : enum_for(:zip, *args))
      if block_given?
         enum.__map__ {|args| yield(*args)}
      else
         enum.to_a
      end
   end
   alias collect map
end
         
module Enumerable
   alias __map__ map
   define_method(:map, Array.new.method(:map))
   alias collect map
end

a.map(b) { |x, y| x*y }
=> [1, 6, 15]

no intermediate object is created (except for the enumerable)
The enumerable acts like a pipe.
Let me take this opportunity to shamelessly point to my
RCR for more Enumerator functionality:
<http://www.rcrchive.net/rcr/RCR/RCR262>

Regards,
KB