From: Robert Klemme Date: 2007-10-03T18:55:03+09:00 Subject: Re: how to add an iterator to a class? On 24.09.2007 05:42, David B. Williams wrote: > Mike Steiner wrote: >> I have a simple class (this is just an example, so ignore any syntax or >> style errors): >> >> class MyArray >> def initialize >> @a = Array.new >> end >> def Push( item ) >> @a.push( item ) >> end >> def GetArray >> return @a >> end >> end >> >> And I have this code: >> >> myarray = MyArray.new >> myarray.Push( 1 ) >> myarray.Push( 2 ) >> >> myarray.GetArray.each do | i | >> puts i >> end >> >> So my question is: How do I replace GetArray with something more >> elegant, >> that gives MyArray a method named .each that I can call directly? >> >> Michael Steiner > > Hi Michael, > > What you want to do is mixin the Enumerable module into your class: > > http://www.ruby-doc.org/core/classes/Enumerable.html > > You then have to define an #each method that yields for each member of > your collection. > > For example: > > class MyArray > include Enumerable > > def initialize > @a = Array.new > end > > def each > for e in @a do > yield e > end > end > end In this simple case (i.e. without filtering or converting) you can even do this: def each(&b) @a.each(&b) self end Also note that conventionally #each returns self. Kind regards robert