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]]
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].
Ruby | Array concat() operation Array#concat() : concat() is a Array class method which returns the array after appending the two arrays together.
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.
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.
Try Array#zip
a.zip(b)
=> [[1,4],[2,5],[3,6]]
While zip
is obviously the most straightforward answer, this also works:
[a, b].transpose
=> [[1, 4], [2, 5], [3, 6]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With