On Sat, May 17, 2003 at 02:00:35AM +0900, Martin DeMello wrote:
> 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

Why not simply use some prefix?
 
 class Module
   def make_collector(*args)
     args.each {|meth|
       module_eval <<-EOF
       alias_method :__foo_bar_baz_#{meth}, :#{meth}
       def #{meth}(*args)
 	retval = []
 	__foo_bar_baz_#{meth}(*args) {|x|
 	  if block_given?
 	    yield x
 	  else
 	    retval << x
 	  end
 	}
       end
       EOF
     }
   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

-- 
 _           _                             
| |__   __ _| |_ ___ _ __ ___   __ _ _ __  
| '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ 
| |_) | (_| | |_\__ \ | | | | | (_| | | | |
|_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_|
	Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

> I'm an idiot..  At least this [bug] took about 5 minutes to find..
Disquieting ...
	-- Gonzalo Tornaria in response to Linus Torvalds's