需要在 Ruby 中将数组拆分为指定大小的子数组 [英] Need to split arrays to sub arrays of specified size in Ruby
本文介绍了需要在 Ruby 中将数组拆分为指定大小的子数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似这样的数组:
I have an array that is something like this:
arr = [4, 5, 6, 7, 8, 4, 45, 11]
我想要一个花哨的方法
sub_arrays = split (arr, 3)
这应该返回以下内容:[[4, 5, 6], [7,8,4], [45,11]]
注意:这个问题不是如何对数组进行分块"的重复.块问题是关于批量处理,这个问题是关于拆分数组.
Note: This question is not a duplicate of "How to chunk an array". The chunk question is asking about processing in batches and this question is about splitting arrays.
推荐答案
arr.each_slice(3).to_a
each_slice
返回一个 Enumerable,所以如果这对你来说足够了,你不需要调用 to_a
.
each_slice
returns an Enumerable, so if that's enough for you, you don't need to call to_a
.
在 1.8.6 中你需要做:
In 1.8.6 you need to do:
require 'enumerator'
arr.enum_for(:each_slice, 3).to_a
如果你只需要迭代,你可以简单地做:
If you just need to iterate, you can simply do:
arr.each_slice(3) do |x,y,z|
puts(x+y+z)
end
这篇关于需要在 Ruby 中将数组拆分为指定大小的子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文