From: Guillaume Marcais Date: 2003-07-09T05:09:40+09:00 Subject: Re: Array.each On Tue, 2003-07-08 at 15:00, Berger, Daniel wrote: > > > Gentelmans: ........(There are any woman around there ?) > > > > I would love to be able to do: > > > > > > a=(1..10) > > With this code, 'a' becomes a single Range. Try: a = *1..10. > > > a.each {| x , y| p x } > > > > 1 > > 3 > > 5 > > 7 > > 9 > > You'll have to redefine each() to yield two elements instead of one in order > to get this behavior. Or you could just use step: > > 0.step(a.length,2){ |i| p a[i] } > > > (IMHO ... following the principle of the least surprise..may it > > should be a native behavior .) > > You mean Ruby should automatically yield as many parameters as the block > expects? You'll have to talk to Matz about that one. :) Something like that? [gus@comp ex]$ cat eachn.rb module Enumerable def each_n(&b) i = [] n = b.arity n = -n if n <= 1 k = n self.each { |x| i << x k -= 1 if k <= 0 b.call(*i) i = [] k = n end } unless i.empty? i += Array.new(n - i.length) b.call(*i) unless i.empty? end end end if __FILE__ == $0 (0..10).each_n { |x| puts "x %s" % x.inspect } (0..10).each_n { |x, y| puts "x %s y %s" % [x.inspect, y.inspect] } (0..10).each_n { |x, y, z| puts "x %s y %s z %s" % [x.inspect, y.inspect, z.inspect] } [].each_n { |x, y| puts "Huh?" } end [gus@comp ex]$ ruby eachn.rb x 0 x 1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 x 9 x 10 x 0 y 1 x 2 y 3 x 4 y 5 x 6 y 7 x 8 y 9 x 10 y nil x 0 y 1 z 2 x 3 y 4 z 5 x 6 y 7 z 8 x 9 y 10 z nil Guillaume. > Regards, > > Dan >