假设我有一个数组
aoa = [1, 2, [3, 4], 5, [6, 7, 8], 9]我想将数组和单个元素提取为如下数组
[[1,2,5,9],[3,4],[6,7,8]] #=>order is not important我试过了,但不确定如何处理单个元素。
aoa.map{|i| i if i.kind_of?(Array)}.compact #=> [[3, 4], [6, 7, 8]] 发布于 2015-05-13 12:30:52
您可以使用隔断 (以及@CarySwoveland指出的splat运算符)。
a, i = aoa.partition{ |i| i.is_a? Array }
# => [[[3, 4], [6, 7, 8]], [1, 2, 5, 9]]
[*a, i]
# => [[3, 4], [6, 7, 8], [1, 2, 5, 9]]发布于 2015-05-13 12:28:25
Enumerable#group_by返回一个Hash,它的值就是您想要的:
aoa.group_by(&:size).values.map(&:flatten)
# => [[1, 2, 5, 9], [3, 4], [6, 7, 8]]@Cary Swoveland指出,使用size进行分组是个坏主意,因为与Fixnum#size大小相同的子数组会导致意外的结果。应该使用group_by(&:class)。
发布于 2015-05-13 15:10:03
nested_a = [[]]
aoa.each {|e| e.is_a?(Array) ? nested_a << e : nested_a[0] << e }
#remove 1st nested array if empty(Occurs if there were no individual elements)
nested_a.shift if nested_a[0].empty?
nested_a # => [[1, 2, 5, 9], [3, 4], [6, 7, 8]]https://stackoverflow.com/questions/30214683
复制相似问题