akrisanov akrisanov - 9 months ago 26
Ruby Question

Get every n-elements of array

I have an array

a = [0, 1, 2, 3, 4, ... , 33]


How to select every n-elements (e.g. six) from the array?

result = [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11], ... ]


P.S. I use Ruby 1.9.

Answer Source

Enumerable#each_slice

Iterates the given block for each slice of elements. If no block is given, returns an enumerator.

e.g.:

(1..10).each_slice(3) {|a| p a}
# outputs below
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10]

Use as:

irb(main):002:0> a =  Array(1..33)
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33]
irb(main):003:0> a.each_slice(5) # no good
=> #<Enumerable::Enumerator:0x47ae6e8>
irb(main):004:0> a.each_slice(5).to_a # good
=> [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33]]