From: Martin DeMello Date: 2003-05-30T06:44:25+09:00 Subject: Re: Iteration - last detection ahoward wrote: > On Thu, 29 May 2003, Martin DeMello wrote: >> 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': That isn't much better, though - you have the overhead of generating an index you never use. It's annoying because the test is guaranteed to only succeed right at the beginning, but you nonetheless have to carry it all the way through. I was even thinking of self-modifying code to get around that :) I suspect that in real terms it's a negligible cost, but it's still inelegant. > 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... Hm - for some reason I thought yield had to yield a single value. Too late at night :) martin