Ruby内部扁平化(数组数组) [英] Ruby inner flatten (array of arrays)

查看:152
本文介绍了Ruby内部扁平化(数组数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似以下的数组

I have an array like the following

[
  [[0, :a], [2, :b]],
  [3, :c],
  [4, :d],
  [[5, :e], [6, :f], [7, :g]]
]

也就是说,一个元素数组可以是(1)2个元素的数组,或者(2)2个元素的数组.

That is, an Array of elements that are either (1) 2-element Arrays, or (2) an Array of 2-element Arrays.

我正在尝试找到一种优雅的方法来扁平化"此数组,以使(2)的元素扩展为根级元素.在此示例中:

I am trying to find an elegant way to "flatten" this array such that elements that are (2) get expanded out into root-level elements. In this example:

[[0, :a], [2, :b], [3, :c], [4, :d], [5, :e], [6, :f], [7, :g]]

这几乎与使用Array#flatten(depth)相似,只是depth需要从内而外,而不是从外而内.

This is almost like using Array#flatten(depth), except depth needs to work from the inside out, rather than the outside in.

实际的数组可能会变得非常大,因此出于性能原因,我不想将(<<)元素以循环方式推入新的Array中.由于某些原因,我无法考虑如何使用mapflattenflat_map或其他更有效的Enumerable方法的任意组合来完成此操作,而无需编写C ++样式的preallocate-and-populate循环.谁能想到一种更Ruby的方式来做到这一点?

The actual arrays can get very large, so I do not want to push (<<) elements onto a new Array in a loop for performance reasons. For some reason I cannot think of how to use any combination of map, flatten, flat_map, or other more efficient Enumerable methods to accomplish this without writing a C++-style preallocate-and-populate loop. Can anyone think of a more Rubyist way to do this?

推荐答案

一种方法是:

array.flatten.each_slice(2).to_a

这篇关于Ruby内部扁平化(数组数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆