From: Martin DeMello Date: 2003-05-30T05:42:57+09:00 Subject: Re: Iteration - last detection 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. martin