From: Rick DeNatale Date: 2006-08-07T05:04:31+09:00 Subject: Re: Iterating over an array n element at a time On 8/6/06, Trans wrote: > > 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. I might be wrong, but I can't see how these parameter markers can be implemented without a lot of changes. The syntax of block literals needs to be changed to allow the markers, then the Proc class needs to be changes so that the methods like select can see the markers, then all the methods in Enumerable (and anywhere else they are reimplemented e.g. Hash), need to be changed to be sensitive to them, and make them "slurpable." It seems like these "slurp indicators" are trying to move the loop control out of the internal iterators, and to make the block look a teeny bit like a java style iterator in some strange sense, which makes the idea seem a little less ruby-like. Martin DeMello's eachn method is a neat trick which makes use of existing mechanisms. but I suspect that making such stuff general isn't such a good idea for Ruby, maybe for a forked language (sluby?) for those who like such stuff. For Ruby, I think that Nakada-san's suggestion is a better way to compose such functionality. -- Rick DeNatale IPMS/USA Region 12 Coordinator http://ipmsr12.denhaven2.com/ Visit the Project Mercury Wiki Site http://www.mercuryspacecraft.com/