[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: how to add an iterator to a class?

David B. Williams

9/24/2007 3:42:00 AM

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/Enume...

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.cybersp...
--
Posted via http://www.ruby-....

1 Answer

Robert Klemme

10/3/2007 9:50:00 AM

0

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/Enume...
>
> 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