简体   繁体   English

如何将红宝石中的阵列切成指定长度的子阵列?

[英]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.

相关问题 如何将一个数组切成不同大小的数组并将它们组合在一起? - How do I slice an array into arrays of different sizes and combine them? Ruby将each_slice放入子数组,如果最后一个子数组的大小与其他子数组不同,则设置默认元素值 - Ruby each_slice into sub arrays and set default element values if last sub-array is different size to other sub-arrays 如何使用 javascript 按行长度过滤数组的 arrays? - How do I filter arrays of an array by row length using javascript? 如何创建不等长数组的数组? - How do i create an array of unequal length arrays? 如何在javascript中将子数组字符串数组转换为子数组数组? - How do i convert an array of sub-array strings to an array of sub-arrays in javascript? 如何按长度对Ruby字符串数组进行排序? - How do I sort a Ruby array of strings by length? 如何在Ruby中将“ values_at”应用于数组数组? - How do I apply “values_at” to an array of arrays in Ruby? 如何以有效的方式获取长度为2或更大的数组的所有子数组? - How to get all sub arrays of an array of length 2 or more in efficient way? 在 Ruby 中排序不符合我对子数组的期望 - Sorting in Ruby doesn't do what I expect with sub arrays 是否有一个Ruby Array方法返回两个子数组:一个指定的大小,另一个剩余的内容? - Is there a Ruby Array method that returns two sub-arrays: one of specified size and another of the remaining contents?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM