From: Mike Stok Date: 2006-05-12T00:03:41+09:00 Subject: Re: each with arguments On 11-May-06, at 10:53 AM, Charles Churchill wrote: > I've found myself writing the following code to address needs I have > processing formatted text files, but is this possible some other and I > am going through foolish gyrations here... > > Here is the code: > > class Array > alias :orig_each :each > def each(cnt = 1, &blk) > if cnt == 1 > orig_each { |x| blk.call(x) } > else > 0.step(self.size - 1,cnt) do |i| > yield(self.slice(i,cnt)) > end > end > end > end > > so I can do things like this > > arr = [ key, value, value, key, value, value, key, value, value, ... ] > arr.each(3) do |key,val1,val2| > #manipulate them as I see fit > end > > Thanks for any help you can give! Have you looked at Enumerable#each_slice which is included in Array? ratdog:~ mike$ ri Enumerable#each_slice -------------------------------------------------- Enumerable#each_slice e.each_slice(n) {...} ------------------------------------------------------------------------ Iterates the given block for each slice of elements. e.g.: (1..10).each_slice(3) {|a| p a} # outputs below [1, 2, 3] [4, 5, 6] [7, 8, 9] [10] Mike -- Mike Stok http://www.stok.ca/~mike/ The "`Stok' disclaimers" apply.