如何展平 Ruby 中的子数组?
How to flatten subarrays in Ruby?
我有以下结构
a = [['a', 'b', 'c'], ['d', 'e', 'f'], [['g', 'h', 'i'], ['l', 'm', 'n']]]
我想获得以下内容:
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]
我试过以下方法:
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']]
我目前找到的解决方案是将初始结构更改为以下格式:
b = [[['a', 'b', 'c']], [['d', 'e', 'f']], [['g', 'h', 'i'], ['l', 'm', 'n']]]
然后调用
b.flatten(1) => [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]
但我能做到这一点只是因为我能够改变 a
的构建方式。我的问题仍然存在:如何从 a
?
开始获得我想要的结果
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']]
其他解决方案:
a.flat_map { |e| e[0].is_a?(Array) ? e : [e] }
#=> [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["l", "m", "n"]]
我有以下结构
a = [['a', 'b', 'c'], ['d', 'e', 'f'], [['g', 'h', 'i'], ['l', 'm', 'n']]]
我想获得以下内容:
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]
我试过以下方法:
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']]
我目前找到的解决方案是将初始结构更改为以下格式:
b = [[['a', 'b', 'c']], [['d', 'e', 'f']], [['g', 'h', 'i'], ['l', 'm', 'n']]]
然后调用
b.flatten(1) => [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]
但我能做到这一点只是因为我能够改变 a
的构建方式。我的问题仍然存在:如何从 a
?
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']]
其他解决方案:
a.flat_map { |e| e[0].is_a?(Array) ? e : [e] }
#=> [["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"], ["l", "m", "n"]]