Trans
8/6/2006 10:56:00 AM
Robert Klemme wrote:
> 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:
Right. But wasn't that what was originally asked for? In any case, I
am only meaning the "chunk" case with my example, but certainly one
could conceive of a notion to "slide" too. The advantage of notation
over more methods is that it works with derivatives. Eg. pseudo code:
[1,1,2,2,3,4].select { |slide(a,b)| a == b }
Otherwise you need a select_slice, select_cons, collect_slice,
collect_cons, and so on.
T.