Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to concatenate array of arrays into one

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.

like image 506
Pedro Cori Avatar asked Nov 26 '11 22:11

Pedro Cori


People also ask

How do you combine arrays in Ruby?

This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).

How do you append an array to another array in Ruby?

In this case, you can use the concat() method in Ruby. concat() is used to join, combine, concatenate, or append arrays. The concat() method returns a new array with all of the elements of the arrays combined into one.

Can you concatenate arrays?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.


2 Answers

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.

like image 189
millimoose Avatar answered Sep 18 '22 17:09

millimoose


Or more generally:

array_of_arrays.reduce(:concat) 
like image 31
d11wtq Avatar answered Sep 17 '22 17:09

d11wtq