From: Robert Klemme Date: 2006-08-06T17:35:12+09:00 Subject: Re: Iterating over an array n element at a time Trans wrote: > Kim Pedersen wrote: >> Is there an elegant way to iterate over an array n elements at a time? >> e.g. something like... >> >> a = [1,1,1,2,2,2,3,3,3] >> >> a.each(3) do |x,y,z| >> print x,y,z,"\n" >> end >> >> prints... >> 111 >> 222 >> 333 >> >> //kim > > enumerator is probably better since it is built-in, but... > > require 'facet/enumerable/each_by' > a = [1,1,1,2,2,2,3,3,3] > a.each_by(3) { |x,y,z| print x,y,z,"\n" } > 111 > 222 > 333 > > But why not have Ruby fill those arguments out automatically? This > already does: > > a = [[1,1,1],[2,2,2],[3,3,3]] > a.each { |x,y,z| print x,y,z,"\n" } > > So couldn't some "slurping" indicator be used? > > a = [1,1,1,2,2,2,3,3,3] > a.each { |(x,y,z)| print x,y,z,"\n" } > > Or something. > > T. > > Note though that your code does something different than each_cons which moves a sliding window while your code iterates in chunks! See: robert@fussel ~ $ ruby -r enumerator -e' %w( 1 2 3 4 5 ).each_cons(2){|a, b| p a, b, "-"} ' "1" "2" "-" "2" "3" "-" "3" "4" "-" "4" "5" "-" robert@fussel ~ $ Kind regards robert