Ruby: How to concatenate array of arrays into one

RubyArraysMultidimensional ArrayConcatenation

Ruby Problem Overview


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?

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

but I wanted to know if there was like a Ruby one-liner which would do it in a cleaner manner.

Thanks for your help.

Ruby Solutions


Solution 1 - Ruby

You're looking for #flatten:

concatenated = array_of_arrays.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.

Solution 2 - Ruby

Or more generally:

array_of_arrays.reduce(:concat)

Solution 3 - Ruby

You can use flatten! method. eg. a = [ 1, 2, [3, [4, 5] ] ] a.flatten! #=> [1, 2, 3, 4, 5]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPedro CoriView Question on Stackoverflow
Solution 1 - RubymillimooseView Answer on Stackoverflow
Solution 2 - Rubyd11wtqView Answer on Stackoverflow
Solution 3 - RubyPankajView Answer on Stackoverflow