From: Mariano Kamp Date: 2006-10-04T03:00:53+09:00 Subject: Re: Using Each to Iterate Hi Jeff, > With all the responses I got here, I figured it out. Thanks to all > of you. > I'll put the relevant source here and what I did, just in case this > helps > others. I have the feeling that you didn't figure it out completely yet. A few small things: > def append(thisGuide) > @guides.push(thisGuide) > self > end Btw. Did you know that you could use "<<" as a method name? > def filter(thisGuide) > @guides.find { |guide| thisGuide == guide.filter } > end Find will only return the first occurrence. find_all will return all occurrences. > def [](index) > @guides[index] if index.kind_of?(Integer) > end Btw. (2) ... you can check if the index is of the right type, probably to check for a coding error, but then you just return nil. So that the error can slip silently. **If** you want to do this checking here, instead of in the unit tests, you might want to raise an exception, but then this would not be necessary as Array would already do that for you. > def each > @guides.find { |guide| guide.filter } > end Here again, you would just find the first occurrence. So the method would be more accurately named "first" or something. Especially since "each" has a well known meaning to Ruby programmers. If you encounter an each method in someone's code you would think that you can pass in a block and this block will be called for *each* element. Sounds complicated? It is not. Really easy stuff. If you implement each, you know about the internal structure of the collection you manage and you know how to make it happen that you can call "yield element" for each of the elements in your collection. Cheers, Mariano