Ruby:如何将数组连接成一个数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8282096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby: How to concatenate array of arrays into one
提问by Pedro Cori
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?
我在 Ruby on Rails (3.1) 中有一个数组数组,其中所有内部数组的大小都不同。有没有一种方法可以轻松地连接所有内部数组以获得一个包含所有项目的大一维数组?
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:
我知道你可以使用 Array::concat 函数来连接两个数组,我可以做一个循环来按顺序连接它们,如下所示:
concatenated = Array.new
array_of_arrays.each do |array|
concatenated.concat(array)
end
but I wanted to know if there was like a Ruby one-liner which would do it in a cleaner manner.
但我想知道是否有像 Ruby one-liner 这样的单行代码可以以更简洁的方式完成。
Thanks for your help.
谢谢你的帮助。
回答by millimoose
You're looking for #flatten:
您正在寻找#flatten:
concatenated = array_of_arrays.flatten
By default, this will flatten the lists recursively. #flattenaccepts an optional argument to limit the recursion depth – the documentation lists examples to illustrate the difference.
默认情况下,这将递归地展平列表。#flatten接受一个可选参数来限制递归深度——文档列出了示例来说明差异。
回答by d11wtq
Or more generally:
或更一般地说:
array_of_arrays.reduce(:concat)
回答by Pankaj
You can use flatten! method. eg.
a = [ 1, 2, [3, [4, 5] ] ]
a.flatten! #=> [1, 2, 3, 4, 5]
你可以使用扁平化!方法。例如。
a = [ 1, 2, [3, [4, 5] ] ]
a.flatten! #=> [1, 2, 3, 4, 5]

