2

Possible Duplicate:
Need to split arrays to sub arrays of specified size in Ruby

What is the best way to segment an array by a given length? What I want is something like 'segment_by' in the following:

[1, 2, 3, 4, 5, 6].segment_by(2)
# => [[1, 2], [3, 4], [5, 6]]

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'].segment_by(3)
# => [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]

What I managed to come up with is the following, but it looks not simple enough:

class Array
    def segment_by i
        (0...length).group_by{|x| x.div(i)}.values.map{|a| a.map{|j| self[j]}}
    end
end

I am using ruby1.9.2. Is there already such method, and it there a better way to do it?

Community
  • 1
  • 1
sawa
  • 165,429
  • 45
  • 277
  • 381

1 Answers1

9

Use each_slice

[1,2,3,4,5,6].each_slice(2).to_a      # => [[1, 2], [3, 4], [5, 6]]
[1,2,3,4,5,6].each_slice(3).to_a      # => [[1, 2, 3], [4, 5, 6]]
cam
  • 14,192
  • 1
  • 44
  • 29