如何在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开始获得我想要的结果?
I have the following structure
a = [['a', 'b', 'c'], ['d', 'e', 'f'], [['g', 'h', 'i'], ['l', 'm', 'n']]]and I want to obtain the following:
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]I've tried the following:
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']]the solution I found, for now, is to change the initial structure to this format:
b = [[['a', 'b', 'c']], [['d', 'e', 'f']], [['g', 'h', 'i'], ['l', 'm', 'n']]]and then call
b.flatten(1) => [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'], ['l', 'm', 'n']]but I could do this only because I was able to change how a was built. My question remains: how to obtain my desired result starting from 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.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']]更多推荐
发布评论