From: Carlos Date: 2004-03-13T04:37:53+09:00 Subject: Re: iterating with multiple values [gabriele renzi , 2004-03-12 19.09 CET] > Hi gurus and nubys, > > Suppose you are dealing with an array like [1,2,3,4], and suppose ypou > want to deal, at any iteration, with 3 values.I mean something like: > > [1,2,3,4].each_3 do |pre,cur,next| > print pre,cur,next,"\n" > end > > nil,nil,1 > nil,1,2 > 1,2,3 > 2,3,4 > 3,4,nil > 4,nil,nil > > What do you think is the best way to this? I can think of adding a > global index and use it to refer explicitly to an element oin the > array, but this is ugly to me.. [...] You can use an array to buffer intermediate results. Something like (not tested): module Enumerable def each_n(n) a = Array.new(n) each do |cur| a.shift a.push cur yield *a end (a.size-1).times do a.shift a.push nil yield *a end end end Good luck.