Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two arrays to create a two dimensional array in ruby

Tags:

arrays

ruby

a = [1, 2, 3]
b = [4, 5, 6]

How would I combine the two arrays in a 2D array?:

[[1, 4], [2, 5], [3, 6]]
like image 922
user1311034 Avatar asked Aug 17 '12 18:08

user1311034


People also ask

How do you create a two dimensional array in Ruby?

For example, Array. new(5) will create an array of 5 nil objects. The second argument gives you a default value, so Array. new(5, 0) will give you the array [0,0,0,0,0].

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

Ruby | Array concat() operation Array#concat() : concat() is a Array class method which returns the array after appending the two arrays together.

How do you create a nested array in Ruby?

To add data to a nested array, we can use the same << , or shovel, method we use to add data to a one-dimensional array. To add an element to an array that is nested inside of another array, we first use the same bracket notation as above to dig down to the nested array, and then we can use the << on it.

How do you initialize an array of arrays in Ruby?

There are two ways to initialize an array: Declare the size of the array with the keyword new and populate it afterward. Declare the array along with its values.


2 Answers

Try Array#zip

a.zip(b)
=> [[1,4],[2,5],[3,6]]
like image 121
Kulbir Saini Avatar answered Oct 11 '22 17:10

Kulbir Saini


While zip is obviously the most straightforward answer, this also works:

[a, b].transpose
=> [[1, 4], [2, 5], [3, 6]]
like image 35
Michael Kohl Avatar answered Oct 11 '22 18:10

Michael Kohl