Accessing Arrays of Arrays
Understand how to work with two-dimensional arrays in Ruby by accessing elements using row and column indices and traversing arrays with nested loops or each methods. This lesson helps you handle array of arrays confidently and write readable, efficient Ruby code.
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 ...