From: "Brian Schröder" Date: 2005-09-01T19:49:07+09:00 Subject: Re: implementing the "each" method for own classes On 01/09/05, Robert Klemme wrote: > Brian Schr�der wrote: > > On 01/09/05, Philipp Huber wrote: > >> actually i did test it with a queue filled with a few elements. as > >> you said the condition for the while loop should be testet at the > >> beginning, otherwise nil could be returned. > >> so my code looks like this: > >> > >> def each > >> node=@head > >> while node=node.next > >> yield node.content > >> end > >> end > >> > >> do you have an example for the second remark, as i don't quite > >> understand what you mean > > Just put "return self" or just "self" in the last line of your method > #each. > > > Sorry for posting something that untested. But as I look again you > > continue to have bugs in your code. > > > > You are missing the first element. The following should work and also > > return self. That allows you to do something like the following: > > That's only true if head is nil for an empty queue. There are > implementations out there (for example java.util.LinkedList) where the > first element is never null. It might be though that it makes sense only > for a doubly linked list. > > > queue.each do | element | element.seen += 1 end.each do | element | > > puts element end > > > > Beware that the above example does not make that much sense, but I do > > not have a better example ready. > > > > def each > > node=@head > > while node > > yield node.content > > node=node.next > > end > > self > > end > > That's what I suggested, isn't it? It is - I'm sorry, I'm task-switching in my mind too fast at the moment. I will concentrate on my thesis now ... best regards, Brian > > Kind regards > > robert > > > -- http://ruby.brian-schroeder.de/ Stringed instrument chords: http://chordlist.brian-schroeder.de/