Ruby multidimensional array Ruby multidimensional array ruby ruby

Ruby multidimensional array


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.


you can pass a block to Array.new

Array.new(n) {Array.new(n,default_value)}

the value that returns the block will be the value of each index of the first array,

so..

Array.new(2) {Array.new(2,5)} #=> [[5,5],[5,5]]

and you can access this array using array[x][y]

also for second Array instantiation, you can pass a block as default value too. so

Array.new(2) { Array.new(3) { |index| index ** 2} } #=> [[0, 1, 4], [0, 1, 4]]


Just a clarification:

arr = Array.new(2) {Array.new(2,5)} #=> [[5,5],[5,5]]

is not at all the same as:

arr = Array.new(2, Array.new(2, 5))

in the later case, try:

arr[0][0] = 99

and this is what you got:

[[99,5], [99,5]]