ruby 将数组拆分为一些子数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7824287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:24:11  来源:igfitidea点击:

Split an array into some sub-arrays

rubyarrays

提问by Zag zag..

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.

回答by Chris Ledet

You can use the #each_slicemethod 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]]

回答by tolitius

check out the slice:

检查切片

big_array.each_slice( 2 ).to_a