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

From there, your class will have all of the methods defined in 
Enumerable.

David B. Williams
http://www.cybersprocket.com
-- 
Posted via http://www.ruby-forum.com/.