create a 3 dimensional array in ruby

To create a 3-dimensional array in Ruby, we can nest Arrays inside Arrays:

main.rb
# initialize a 3d array with the size of 2x3x4
three_dimensional_array = Array.new(2) { Array.new(3) { Array.new(4) } }

# set the value of an element in the array
three_dimensional_array[0][2][3] = 5

# get the value of an element in the array
value = three_dimensional_array[0][2][3]
286 chars
9 lines

In this example, we create a 3-dimensional array with a size of 2x3x4, which means we have two 2-dimensional arrays that contain three 1-dimensional arrays with four elements each.

We can set the value of an element in the array by using the bracket notation and passing in the indices of the element we want to modify. In this case, we set the value of the element at index [0][2][3] to 5.

Similarly, we can retrieve the value of an element in the array by using the bracket notation and passing in the indices of the element we want to access. In this case, we retrieve the value at index [0][2][3] and assign it to a variable named value.

gistlibby LogSnag