From: martindemello@... (Martin DeMello) Date: 2003-05-17T02:00:35+09:00 Subject: make_collector Got tired of perpetually writing if-then-else code to accumulate the results of an iterator and return an array if no block was passed in. (The somewhat hacked-up gensym class could probably use work - how threadsafe is Singleton? Would using a class instance variable be better?) -------------------------------------- require 'singleton' class Gensym include Singleton def initialize @n = 0 end def next @n += 1 "G#{@n}".intern end end def gensym Gensym.instance.next end class Module def make_collector(*args) args.each {|meth| oldmeth = gensym module_eval <<-here alias #{oldmeth} #{meth} def #{meth}(*args) retval = [] #{oldmeth}(*args) {|x| if block_given? yield x else retval << x end } end here } end end class Foo def initialize @ary = (1..10).to_a end def traverse @ary.each {|x| yield x} end make_collector(:traverse) end a = Foo.new a.traverse {|x| p x} p a.traverse