开发者

Get every n-elements of array

开发者 https://www.devze.com 2023-02-14 10:57 出处:网络
How to select every n-elements (e开发者_Python百科.g. six) of an array using Ruby 1.9+? Example:

How to select every n-elements (e开发者_Python百科.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]]
0

精彩评论

暂无评论...
验证码 换一张
取 消