From: Paul Brannan Date: 2003-05-30T22:55:00+09:00 Subject: Re: Iteration - last detection On Fri, May 30, 2003 at 06:12:38AM +0900, Dave wrote: > this might work for you, it has simplicity going for it. > > module Enumerable > def each_but_last(&block) > elements = entries > last = elements.pop > elements.each &block > return last > end > end > > last = %w{ one two three }.each_but_last { |i| puts "each_but_last #{i}" } > puts "last #{last}" I like that this solution lacks a flag to indicate whether I'm on the last element; this makes it easy to use. I don't like that all the elements are stored in a temporary array. Combining this with Martin's idea, I get: module Enumerable def each_but_last prev = nil curr = nil each do |curr| yield prev if prev prev = curr end return prev end end It uses less memory, but: 1) It's surprisingly slower 2) Both solutions have the problem of not being able to distinguish between [] and [nil]. Paul