如何在Ruby中压缩子数组?

coo*_*sse 4 ruby arrays flatten

我有以下结构

a = [['a', 'b', 'c'], ['d', 'e', 'f'], [['g', 'h', 'i'], ['l', 'm', 'n']]]
Run Code Online (Sandbox Code Playgroud)

我想获得以下内容:

[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]
Run Code Online (Sandbox Code Playgroud)

我尝试过以下方法:

a.flatten => ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'l', 'm', 'n']

a.flatten(1) => ['a', 'b', 'c', 'd', 'e', 'f', ['g', 'h', 'i'], ['l', 'm', 'n']]
Run Code Online (Sandbox Code Playgroud)

我现在找到的解决方案是将初始结构更改为以下格式:

b = [[['a', 'b', 'c']], [['d', 'e', 'f']], [['g', 'h', 'i'], ['l', 'm', 'n']]]
Run Code Online (Sandbox Code Playgroud)

然后打电话

b.flatten(1) => [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]
Run Code Online (Sandbox Code Playgroud)

但我这样做只是因为我能够改变a建造方式.我的问题仍然存在:如何从中获得我想要的结果a?

Ale*_*kin 6

a.each_with_object([]) do |e, memo|
  e == e.flatten ? memo << e : e.each { |e| memo << e }
end
#? [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]
Run Code Online (Sandbox Code Playgroud)