Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get every n-elements of array

How to select every n-elements (e.g. six) of an array using Ruby 1.9+? Example:

a = [0, 1, 2, 3, 4, ... , 33]
# solution
# => [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11], ... ]
like image 611
akrisanov Avatar asked Mar 03 '11 17:03

akrisanov


1 Answers

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]]
like image 154
Mark Rushakoff Avatar answered Oct 16 '22 14:10

Mark Rushakoff