Accessing Arrays of Arrays
Learn how to access two-dimensional arrays in Ruby.
We'll cover the following
How to access two-dimensional arrays
There is a trick while accessing two-dimensional arrays. When accessing this type of array, we need to access the row first and the column next. From the previous lessons, we learned how to access a one-dimensional array:
puts arr[4]
Or, if we want to change the value:
arr[4] = 123
Now, 4
is the index. With 2D arrays, we need to use double square brackets. For example, the following code will change the value of the cell in the fifth row and the ninth column:
arr[4][8] = 123
For a long time in school, we were told that the coordinates of some area are usually defined as (x, y) in mathematics, where “x” is the position on a horizontal axis (a specific column), and “y” is a position on a vertical axis (a specific row). However, accessing arrays is a bit confusing because we need to access the row first and the column next, or in other words, by using (y, x).
To get a better feeling of how it works, we can break down this expression into multiple lines:
row = arr[4] # Get the entire array on fifth row into variable
row[8] = 123 # Change the ninth cell to 123
This is the way to print the value of the fifth row and the ninth column:
row = arr[4] # Get entire row into variable
column = row[8] # Get the value of cell into another variable
puts column # Print this variable
Get hands-on with 1400+ tech skills courses.