如何在Ruby中压扁子数组?(How to flatten subarrays in Ruby?)

编程入门 行业动态 更新时间:2024-10-26 02:27:56
如何在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']]

更多推荐

本文发布于:2023-07-30 23:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340307.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   压扁   如何在   subarrays   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!