我有一个数组:
array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
如何对数组的每个n个元素进行分组?例如,对于3:
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
我写了这段代码,但是很丑陋:
array.each_with_index.group_by { |e, i| i % 3}.map {|h| h[1].map { |e| e[0] }}
尼克·维斯(Nick Veys)的回答最为直接,但这是另一种方式。
array.group_by.with_index{|_, i| i % 3}.values
#=> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句