Ruby multidimensional array

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

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.


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

There are two ways to initialize multi array (size of 2). All the another answers show examples with a default value.

Declare each of sub-array (you can do it in a runtime):

multi = []
multi[0] = []
multi[1] = []

or declare size of a parent array when initializing:

multi = Array.new(2) { Array.new }

Usage example:

multi[0][0] = 'a'
multi[0][1] = 'b'
multi[1][0] = 'c'
multi[1][1] = 'd'

p multi # [["a", "b"], ["c", "d"]]
p multi[1][0] # "c"

So you can wrap the first way and use it like this:

@multi = []
def multi(x, y, value)
  @multi[x] ||= []
  @multi[x][y] = value
end

multi(0, 0, 'a')
multi(0, 1, 'b')
multi(1, 0, 'c')
multi(1, 1, 'd')

p @multi # [["a", "b"], ["c", "d"]]
p @multi[1][0] # "c"