From: ahoward Date: 2002-11-15T10:41:45+09:00 Subject: Re: Array#next - Enumerable#next ? On Fri, 15 Nov 2002, Paul Brannan wrote: > One problem here is that I can't tell the difference between iterating > over a nil object in an array (e.g. if I have an array [1, 2, 3, nil, > 4]) and hitting the end of the array. This is pretty easy to fix; > change: > return nil > > to: > return DoneIterating [snip] yes. this is a good idea [snip] > A more serious problem here is that code that uses next() is not > reentrant; if you have a method that is iterating over an array, you'd > better not call another method that also iterates over that array. > E.g.: > > def print_array(arr) > while (obj = arr.next) != DoneIterating do > puts obj > end > end > > def print_all_ocurrances(arr, x) > while (obj = arr.next) != DoneIterating do > if x == obj then > print "Found object x in array " > print_array arr > puts > end > end > end [snip] i don't view this as a problem - you are viewing the next method as an iterator, which in definitively is not. it is an instance method of Array, and uses instance variables. i would define Array#next as the the next object the Array is willing to give me. this relies on instance variables, just like Array#size. if you call a method manipulating Array#size, from another method manipulating Array#size - would you be suprised that size had changed? this is good argument for iterator classes i suppose : one needs a separte object for tracking state. however, i've been using that method quite a bit - it's usefull because it's minimal. i will check out the links you sent. thanks. -a -- ==================================== | Ara Howard | NOAA Forecast Systems Laboratory | Information and Technology Services | Data Systems Group | R/FST 325 Broadway | Boulder, CO 80305-3328 | Email: ahoward@fsl.noaa.gov | Phone: 303-497-7238 | Fax: 303-497-7259 ====================================