Maybe it's just my lack of abilities to find stuff here that is the problem, but I can't find anything about how to create multidimensional arrays in Ruby.
Could someone please give me an example on how to do it?
Ruby does not have a built-in datatype for multidimensional arrays. However, they can be initialized and accessed as nested layers of multiple arrays. A 2-dimensional array would be an array of arrays, a 3-dimensional array would be an array of arrays of arrays, and so on for each dimension.
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.
Accessing Elements of Two-Dimensional Arrays: Elements in Two-Dimensional arrays are accessed using the row indexes and column indexes. Example: int x[2][1]; The above example represents the element present in the third row and second column.
Strictly speaking it is not possible to create multi dimensional arrays in Ruby. But it is possible to put an array in another array, which is almost the same as a multi dimensional array.
This is how you could create a 2D array in Ruby:
a = [[1,2,3], [4,5,6], [7,8,9]]
require 'narray' b = NArray[ [1,2,3], [4,5,6], [7,8,9] ]
Use a[i][j]
to access the elements of the array. Basically a[i]
returns the 'sub array' stored on position i
of a
and thus a[i][j]
returns element number j
from the array that is stored on position i
.
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