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