Ger*_*Cas 4 ruby group-by slice
我有arr我想按 array 中给出的索引分组的数组idx。我的意思是,
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)
您可以使用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_after和with_index。