From: Rick DeNatale Date: 2006-08-06T13:11:42+09:00 Subject: Re: Iterating over an array n element at a time On 8/5/06, Martin DeMello wrote: > On 8/6/06, Trans wrote: > > 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. > > require 'enumerator' > > module Enumerable > def eachn(&block) > n = block.arity > each_slice(n) {|i| block.call(*i)} > end > end > > a = (1..10).to_a > a.eachn {|x,y,z| p [x,y,z]} Nice! As it turns out that *i in the block.call invocation isn't needed. The proc call method does the right thing in this case. Also there's no need to turn the range into an array, it'll work directly since ranges mixin Enumerable -- Rick DeNatale