获取数组的每个n元素

时间:2011-03-03 17:57:14

标签: arrays ruby iteration enumeration

如何使用Ruby 1.9+选择数组的每个n元素(例如六个)?例如:

a = [0, 1, 2, 3, 4, ... , 33]
# solution
# => [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11], ... ]

1 个答案:

答案 0 :(得分:35)

Enumerable#each_slice

  

迭代每个给定的块   切片的元素。如果没有阻止   给定,返回一个枚举器。

     

e.g:

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

用作:

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]]