I find myself using the following snippet often when grouping an Array into
smaller arrays of [less than or equal to] a certain number for various
def group threshold
result = 
self.each do |item|
result <<  if result.last.length == threshold
result << 
result.last << item
This allows me to do the following:
irb(main):002:0> [1,2,3,4,5,6,7,8,9,10].group 3
[[1, 2, 3], [4, 5, 6], [7, 8, 9], ]
Is there a better way to do this?
I don’t know if it’s better, but just to share the incarnation
of this that I’ve got in my scraps-of-code library:
res = 
0.step(size - 1, n) do |i|
s = slice(i … i + n)
yield s if block_given?
=> [[1, 2, 3], [4, 5, 6], [7, 8, 9], ]
The yielding was just in case one wanted to do something with each
sub-array in a block.
On Wed, 4 Sep 2002, Bruce Williams wrote:
David Alan Black | Register for RubyConf 2002!
home: email@example.com | November 1-3
work: firstname.lastname@example.org | Seattle, WA, USA
Web: http://pirate.shu.edu/~blackdav | http://www.rubyconf.com