From: ahoward Date: 2003-05-30T06:03:47+09:00 Subject: Re: Iteration - last detection On Thu, 29 May 2003, Martin DeMello wrote: > Orion Hunter wrote: > > Is there any built in functionality for iteration that will allow me to > > detect when I am on the last element? This would not be hard for an Array, > > using array.length, but what about a Hash? How would I know when I am at > > the last element? > > Not built in, but this should work: > > module Enumerable > def each_with_lastp # no shortage of nicer names, I'm sure :) > flag = nil > i = nil > each {|j| > yield [i, false] if flag > i = j > flag = true > } > yield [i,true] > end > end > > a = [1,2,3,4,5,6,7,8,9] > a.each_with_lastp {|i, last| > print i > print last ? "" : "," > } > > It's rather crude, in that there's the overhead of a call to 'if flag' > with every iteration, but I couldn't think of a way around that. you could use each_with_index to avoid the flag - but not th 'if': module Enumerable def each_with_last(&block) l = nil each_with_index do |e, i| block.call l, false if i > 0 l = e end block.call l, true end end btw. if you don't mind me asking, why 'yield [i,true]'? i remember some posts awhile back about how params get passed to blocks and it was very non-intuitive regarding list assignment and all... -a -- ==================================== | Ara Howard | NOAA Forecast Systems Laboratory | Information and Technology Services | Data Systems Group | R/FST 325 Broadway | Boulder, CO 80305-3328 | Email: ara.t.howard@fsl.noaa.gov | Phone: 303-497-7238 | Fax: 303-497-7259 | ~ > ruby -e 'p % ^) .intern' ====================================