Ruby:如何将数组的数组连接成一个 [英] Ruby: How to concatenate array of arrays into one
问题描述
我在Ruby on Rails(3.1)中有一个数组数组,其中所有内部数组的大小都不同.有没有一种方法可以轻松地将所有内部数组连接起来,使所有项目变成一个大一维数组?
I have an array of arrays in Ruby on Rails (3.1) where all the internal arrays are of different size. Is there a way to easily concatenate all the internal arrays to get one big one dimesional array with all the items?
我知道您可以使用Array :: concat函数来连接两个数组,并且我可以做一个循环来依次连接它们,就像这样:
I know you can use the Array::concat function to concatenate two arrays, and I could do a loop to concatenate them sequentially like so:
concatenated = Array.new
array_of_arrays.each do |array|
concatenated.concat(array)
end
但是我想知道是否有像Ruby这样的单线纸可以更清洁地完成它.
but I wanted to know if there was like a Ruby one-liner which would do it in a cleaner manner.
感谢您的帮助.
推荐答案
You're looking for #flatten
:
concatenated = array_of_arrays.flatten
默认情况下,这将递归地平铺列表. #flatten
接受一个可选参数来限制递归深度–文档列出了一些示例来说明差异.
By default, this will flatten the lists recursively. #flatten
accepts an optional argument to limit the recursion depth – the documentation lists examples to illustrate the difference.
这篇关于Ruby:如何将数组的数组连接成一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!