From: 7stud -- Date: 2007-09-24T13:22:47+09:00 Subject: Re: how to add an iterator to a class? Mike Steiner wrote: > > 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? > each() is an "iterator". An iterator is a method that uses a "yield statement". A yield statement acts similar to a method call, and looks like this: yield some_val yield calls the block and sends it the argument specified to the right of 'yield'. The method that contains the yield statement, i.e. each(), halts and waits for the block to finish executing, and then execution continues in the method. That interaction is very similar to a method that calls another method: def greet sleep(2) puts "hello" sleep(5) end def start greet x = 10 puts x end start If you run that code, you'll see that the method start() waits for greet() to finish executing before it outputs 10. yield works similarly: execution does not continue in the method that contains the yield statement, e.g. each(), until the block that the yield statement called finishes executing. So, you need to define a method called each, and inside each you are going to use a yield statement that sends values to a block. What values? The values are the elements of your array. Since you are generally going to need to yield more than one value, i.e. your array will have more than one element in it, you can put your yield statement inside a loop: class MyArray def initialize @a = Array.new end def push( item ) @a.push( item ) end def each count = 0 while elmt = @a[count] yield elmt count += 1 end end end arr = MyArray.new arr.push(1) arr.push(2) arr.push(3) arr.each{|elmt| puts elmt +2} -- Posted via http://www.ruby-forum.com/.