如何按索引对数组元素进行分组?

Ger*_*Cas 4 ruby group-by slice

我有arr我想按 array 中给出的索引分组的数组idx。我的意思是,

  • 子数组 1 将在索引 1 处结束
  • 子数组 2 将在索引 5 处结束
  • 子数组 3 将在索引 7 处结束
  • 子数组 N 将从索引 8 处的元素到最后一个元素形成 arr

使用我当前的代码,我可以将第一个子数组与idxidx[0] = 1 的第一个索引进行分组。

那么,如何复制数组中的所有索引idx?提前致谢。

我当前的代码和输出是这样的:

idx = [1,5,7]
arr = ['a','b','c','d','e','f','g','h','i','j','k']

arr.group_by.with_index { |z, i| i <= idx[0] }.values
=> [["a", "b"], ["c", "d", "e", "f", "g", "h", "i", "j", "k"]]
Run Code Online (Sandbox Code Playgroud)

我想要的输出是这样的:

output   --> [["a", "b"], ["c", "d", "e", "f"], ["g", "h"], ["i", "j", "k"]]

#Indexes -->    0    1      2    3    4    5      6    7      8    9    10  
Run Code Online (Sandbox Code Playgroud)

Ste*_*fan 6

您可以使用slice_after在索引位于的每个项目之后对数组进行切片idx

idx = [1, 5, 7]
arr = %w[a b c d e f g h i j k]

arr.enum_for(:slice_after).with_index { |_, i| idx.include?(i) }.to_a
#=> [["a", "b"], ["c", "d", "e", "f"], ["g", "h"], ["i", "j", "k"]]
Run Code Online (Sandbox Code Playgroud)

enum_for是(不幸的是)需要链接slice_afterwith_index