From: Mike Stok Date: 2001-11-30T23:24:36+09:00 Subject: [ruby-talk:27068] Re: Using Enumerable On Fri, 30 Nov 2001, Peter Hickman wrote: > Thanks to all who replied, like all ruby it was alot simpler than I > thought. > > class Fred > include Enumerable > > def initialize > @end = 10 > @pointer = 0 > end > > def each > while @pointer != @end do > @pointer += 1 > yield @pointer > end > @pointer = 0 > end > end Be careful that the use of an instance variable means that you may be surprised by the behaviour of code like fred = Fred.new fred.each { |f1| puts "f1 is #{f1}" fred.each { |f2| puts "f2 is #{f2}" } } as the two iterators "share" @pointer and don't play well together. Using code like def each 0.upto(@end) { |pointer| yield pointer } end allows the iterators to be independent of each other. Mike -- mike@stok.co.uk | The "`Stok' disclaimers" apply. http://www.stok.co.uk/~mike/ | GPG PGP Key 1024D/059913DA mike@starnix.com | Fingerprint 0570 71CD 6790 7C28 3D60 http://www.starnix.com/ | 75D2 9EC4 C1C0 0599 13DA