Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby multidimensional array

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?

like image 658
andkjaer Avatar asked Aug 10 '11 16:08

andkjaer


People also ask

How do you create a multidimensional array in Ruby?

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.

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 are multidimensional arrays accessed?

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.


1 Answers

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]] 


As stated in the comments, you could also use NArray which is a Ruby numerical array library:
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.

like image 103
Veger Avatar answered Sep 28 '22 04:09

Veger