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], ... ]
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With