Related Tags

ruby
array

# How multi-dimensional arrays are initialized and accessed in Ruby

Sheza Munir

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.

### Initialization

There are two ways to initialize an array:

1. Declare the size of the array with the keyword new and populate it afterward.
2. Declare the array along with its values.

To initialize multidimensional arrays, both of these methods can be used.

### Initializing a 2D array

arr2D = Array.new(2){Array.new(3)}
// or
arr2D = [[0,1,6],[2,3,8]]


### Initializing a 3D array

arr3D = a = Array.new(2) { Array.new(3) { Array.new(4) } }
// or
arr3D =
[
[[1,2,3,4],
[1,2,3,4],
[1,2,3,4]],
[[1,2,3,4],
[1,2,3,4],
[1,2,3,4]],
]


For every new dimension that is added, an extra pair of brackets is used to represent the new layer.

### Accessing the array

Arrays are accessed via indexing. The method used for a one-dimensional array can be extended by using one more pair of indexing brackets per dimension. For a one-dimensional array:

puts arr1D[1]
//this would print the element at index 1


Consider the arrays in geometric form.

A 2D array would be a plane with rows and columns. The first pair of indexing brackets refers to the row number and the second refers to the column number.

puts arr2d[0][1]
//this would print the element at 0th row and 1st column


A 3D array would be similar to a 3-dimensional cuboid. Another pair of brackets would now refer to the position of the element in the array at the specified row and column. For example:

puts arr3d[0][1][2]
//This will print the element at index 2 of the array at 0th row and 1st column.


### Code

The following code shows how multidimensional arrays can be initialized and accessed.


#declaring a multidimensional array directly
arr2D = [[0,1,6],[2,3,8]]

#allocating space for the array
arr3D = a = Array.new(2) { Array.new(3) { Array.new(4) } }

# populating the array
arr3D =
[
[[1,2,3,4],
[1,2,3,4],
[1,2,3,4]],
[[1,2,3,4],
[1,2,3,4],
[1,2,3,4]],
]

puts "Element at 0th row and 1st column of 2D array: ", arr2D[0][1]
puts "Element at index 2 of the array at 0th row and 1st column: ",arr3D[0][1][2]

RELATED TAGS

ruby
array

CONTRIBUTOR

Sheza Munir