How to declare an empty 2-dimensional array in ruby?
You could also initialize passing a value:
Array.new(3) { Array.new(3) { '0' } }
Output:
[
["0", "0", "0"],
["0", "0", "0"],
["0", "0", "0"]
]
You can do:
width = 2
height = 3
Array.new(height){Array.new(width)} #=> [[nil, nil], [nil, nil], [nil, nil]]
To declare 2d array in ruby, Use following syntax with initialization value
row, col, default_value = 5, 4, 0
arr_2d = Array.new(row){Array.new(col,default_value)}
=> [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]
We can do any level of nesting, like for 3d array(5 x 4 x 2): you can pass block to initialize array in most inner Array
z = 2
arr_3d = Array.new(row){Array.new(col){Array.new(z){|index| index}}}
=> [[[0, 1], [0, 1], [0, 1], [0, 1]],
[[0, 1], [0, 1], [0, 1], [0, 1]],
[[0, 1], [0, 1], [0, 1], [0, 1]],
[[0, 1], [0, 1], [0, 1], [0, 1]],
[[0, 1], [0, 1], [0, 1], [0, 1]]]
Now, you can access its element using [] operator like arr_2d[0][1], actually its array of arrays