[英]How do I slice an array in ruby into sub arrays of a specified length?
I'd like to split an array into sub arrays of a specified length. 我想将一个数组拆分为指定长度的子数组。
I know that .each_slice will chunk an array into equal length subarrays with the remainder leftover like so: 我知道.each_slice会将一个数组分块成相等长度的子数组,剩余的像这样:
a = [1,2,3,4,5,6,7,8,9,10]
a.each_slice(3).to_a => [[1,2,3],[4,5,6],[7,8,9],[10]]
However, say I want the output like this: 但是,说我想要这样的输出:
=> [[1],[2,3],[4,5,6],[7,8,9,10]]
Is there a method in ruby for slicing an array into different specified lengths depending on the arguments you give it? ruby中有没有一种方法可以根据您提供的参数将数组切成不同的指定长度?
Try this 尝试这个
a = [1,2,3,4,5,6,7,8,9,10]
slices = [1,2,3,4].map { |n| a.shift(n) }
This slices the array into pieces 这将数组切成碎片
NB, this mutates the original array. 注意,这会改变原始数组。
I cannot see how to improve on @akuhn's answer, but here are a couple of other methods that could be used. 我看不到如何改善@akuhn的答案,但是这里有一些其他可以使用的方法。
a = [1,2,3,4,5,6,7,8,9,10,11]
slice_sizes = [1,2,3,4]
#1 Stab out slices #1刺出切片
def variable_slice(a, slice_sizes)
last = 0
slice_sizes.each_with_object([]) do |n,arr|
arr << a[last,n]
last += n
end
end
variable_slice(a, slice_sizes)
#=> [[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]
#2 Use recursion #2使用递归
def variable_slice(a, slice_sizes)
return [] if slice_sizes.empty?
i, *rest = slice_sizes
[a.first(i)].concat variable_slice(a[i..-1], rest)
end
variable_slice(a, slice_sizes)
#=> [[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.