Grouping an Array

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
purposes.

class Array
def group threshold
result = []
self.each do |item|
begin
result << [] if result.last.length == threshold
rescue NameError
result << []
end
result.last << item
end
result
end
end

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], [10]]

Is there a better way to do this?

  • B
···


Bruce Williams http://www.codedbliss.com
iusris/#ruby-lang bruce@codedbliss.com

Hello –

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
purposes.

class Array
def group threshold
result = []
self.each do |item|
begin
result << [] if result.last.length == threshold
rescue NameError
result << []
end
result.last << item
end
result
end
end

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], [10]]

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:

class Array
def in_slices_of(n)
res = []
0.step(size - 1, n) do |i|
s = slice(i … i + n)
yield s if block_given?
res.push s
end
res
end
end

[1,2,3,4,5,6,7,8,9,10].in_slices_of(3)

=> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

The yielding was just in case one wanted to do something with each
sub-array in a block.

David

···

On Wed, 4 Sep 2002, Bruce Williams wrote:


David Alan Black | Register for RubyConf 2002!
home: dblack@candle.superlink.net | November 1-3
work: blackdav@shu.edu | Seattle, WA, USA
Web: http://pirate.shu.edu/~blackdav | http://www.rubyconf.com

I like the yielding. I think I’ll add that. :slight_smile:

···

On Tuesday 03 September 2002 07:13 pm, dblack@candle.superlink.net wrote:

The yielding was just in case one wanted to do something with each
sub-array in a block.

David


Bruce Williams http://www.codedbliss.com
iusris/#ruby-lang bruce@codedbliss.com