Possible Duplicate:
How to split (chunk) a Ruby array into parts of X elements?可能重复:如何将Ruby数组拆分(块)成X个元素的部分?
I would like to split an array into an array of sub-arrays.
我想将一个数组拆分成一个子数组。
For example,
例如,
big_array = (0...6).to_a
How can we cut this big array into an array of arrays (of a max length of 2 items) such as:
我们如何将这个大数组切割成一个数组(最大长度为2项),例如:
arrays = big_array.split_please(2)
Where...
哪里...
arrays # => [ [0, 1],
[2, 3],
[4, 5] ]
Note: I ask this question, 'cause in order to do it, I'm currently coding like this:
注意:我问这个问题,'因为为了做到这一点,我目前编码如下:
arrays = [
big_array[0..1],
big_array[2..3],
big_array[4..5]
]
...which is so ugly. And very unmaintainable code, when big_array.length > 100
.
......这太丑了。当big_array.length> 100时,代码非常难以维护。
2 个解决方案
#1
14
You can use the #each_slice
method on the array
您可以在阵列上使用#each_slice方法
big_array = (0..20).to_a
array = big_array.each_slice(2).to_a
puts array # [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11], [12, 13], [14, 15], [16, 17], [18, 19], [20]]
#1
14
You can use the #each_slice
method on the array
您可以在阵列上使用#each_slice方法
big_array = (0..20).to_a
array = big_array.each_slice(2).to_a
puts array # [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11], [12, 13], [14, 15], [16, 17], [18, 19], [20]]