From: "Peña, Botp" Date: 2003-07-09T17:56:38+09:00 Subject: Re: Array.each Brian Candler [mailto:B.Candler@pobox.com] wrote: > > > > a=(1..10) > > a.each {| x , y| p x } > > > > 1 > > 3 > > 5 > > 7 > > 9 > > A more general pattern might be: > > module Enumerable > def each_group(n=1) > res = [] > each do |i| > res << i > if res.size >= n > yield res > res = [] > end > end > yield res if res.size > 0 > end > end > > By making it part of 'Enumerable' and only depending on > 'each', it works for any enumerable class: > > (1..10).each_group(2) { |x,y| puts x } # prints 1,3,5,7,9 cool, but why not use #arity for block's param count, no? I would then use the param for the default like... C:\family\ruby>type a1.rb #class Array module Enumerable def each_group(defval=nil,&block) n = block.arity res = [] each do |i| res << i if res.size >= n yield res res = [] end end if res.size > 0 res << defval until res.size >= n yield res end end end # what follows are just testing x = '(1..8).to_a.each_group {|x,y,z| p "x = #{x}; y = #{y.inspect}; z = #{z.inspect}"}' p "running #{x} using default = nil" eval x p '-----------' x = '(1..7).to_a.each_group(9999) {|x, y,z| p "x = #{x}; y = #{y.inspect} ; z= #{z.inspect}"}' p "running #{x} using default = 9999" eval x p '-----------' x = '(1..5).to_a.each_group([1,2]) {|x, y,z| p "x = #{x}; y = #{y.inspect} ; z = #{z.inspect}"}' p "running #{x} using default an array [1,2]" eval x p '-----------' x = '(1..2).to_a.each_group({"test"=>1}) {|x, y,z| p "x = #{x}; y = #{y.inspect} ; z = #{z.inspect}"}' p 'running #{x} using default a hash {"test"=>1}' eval x p '-----------' x = '(1..1).to_a.each_group("hehehe") {|x, y,z| p "x = #{x}; y = #{y.inspect} ; z = #{z.inspect}"}' p "running #{x} using default a string 'hehehe' " eval x #and outputs... C:\family\ruby>ruby a1.rb "running (1..8).to_a.each_group {|x,y,z| p \"x = #{x}; y = #{y.inspect}; z =#{z.inspect}\"} using default = nil" "x = 1; y = 2; z = 3" "x = 4; y = 5; z = 6" "x = 7; y = 8; z = nil" "-----------" "running (1..7).to_a.each_group(9999) {|x, y,z| p \"x = #{x}; y = #{y.inspect}; z = #{z.inspect}\"} using default = 9999" "x = 1; y = 2 ; z = 3" "x = 4; y = 5 ; z = 6" "x = 7; y = 9999 ; z = 9999" "-----------" "running (1..5).to_a.each_group([1,2]) {|x, y,z| p \"x = #{x}; y = #{y.inspect} ; z = #{z.inspect}\"} using default an array [1,2]" "x = 1; y = 2 ; z = 3" "x = 4; y = 5 ; z = [1, 2]" "-----------" "running #{x} using default a hash {\"test\"=>1}" "x = 1; y = 2 ; z = {\"test\"=>1}" "-----------" "running (1..1).to_a.each_group(\"hehehe\") {|x, y,z| p \"x = #{x}; y = #{y.inspect} ; z = #{z.inspect}\"} using default a string 'hehehe' " "x = 1; y = \"hehehe\" ; z = \"hehehe\"" > Regards, > > Brian. kind regards -botp