Michael Saltzman wrote:
> Am new to Ruby and have the folloiwng Question.
> 
> I have a class, say Collect, and I want to mixin Enumerable. How do I 
> write the each method in Collect?
> 
> class Collect
> 	include Enumerable
> 	def initialize()
> 		@array = Array.new(0)
> 		@ct = 0
> 	end
> 	def add(item)
> 		@array.push(item)
> 		@ct += 1
> 	end
> 	def howmany
> 		@ct
> 	end
> 	def each
> 	#
> 	#	Not sure how to do this????
> 	#
> 	end
> end
> 

You have several options:

class Collect
   include Enumerable

   def initialize()
     @array = []
   end

   def add(item)
     @array.push(item)
     self
   end

   alias :<< :add

   def howmany
     @array.size
   end

   # option 1: use yield
   def each_1
     @array.each {|x| yield x}
     self
   end

   # option 2: delegate to Array's each
   def each_2(&b)
     @array.each(&b)
     self
   end
end

Kind regards

	robert