From: Robert Date: 2003-05-31T18:56:47+09:00 Subject: Re: Iteration - last detection Great solution. Thank's for showing how simple some things become if you look at them from the right perspective. robert "Brian Candler" schrieb im Newsbeitrag news:20030530123215.GA8185@uk.tiscali.com... > On Fri, May 30, 2003 at 08:33:15PM +0900, Carlos wrote: > > > Is there any built in functionality for iteration that will allow me to > > > detect when I am on the last element? > .. > > Here is a module that implements it, but you should include it in every > > class where you want #each to behave that way :-/. > .. > > def EachWithLast.append_features(klass) > > old_each="each_"+rand(10000).to_s+Time.now.usec.to_s > > klass.class_eval <<-FINISH > > Err??! > > I must be missing something; why is this not an incredibly simple thing to > achieve? > > module Enumerable > def each_with_last > prev = nil > each_with_index do |item,index| > yield prev,false if index > 0 > prev = item > end > yield prev,true > end > end > > irb(main):011:0> [1,2,3,4,5].each_with_last do |a,b| puts a,b; end > 1 > false > 2 > false > 3 > false > 4 > false > 5 > true > > It was Nobu's comment that this should work with IO which made me think it > must work this way: you simply keep reading items until there are no more > (eof in the case of IO), and then you yield with 'true' for the last one. > > But like I say, I might have missed something... > > Regards, > > Brian. >