Ruby Nested Arrays
A nested array is an array that holds other arrays as its items. Rows of a grid are a common shape for a nested array.
A grid of three rows
The grid holds three rows of three numbers each. p prints the whole grid as one value.
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
p gridReading one cell
The first index picks row 1, which holds 4, 5 and 6. The second index picks place 2 in that row.
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
puts grid[1][2]Printing whole rows
One index reads a whole row. p shows the first row and the last row as arrays.
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
p grid[0]
p grid[2]Changing one cell
Two indexes and a new value change one cell. p shows the grid with 99 in the middle cell.
grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
grid[1][1] = 99
p gridExample
grid = [[2, 4, 6], [1, 3, 5], [7, 8, 9]]
puts grid[0][2]
grid[2][0] = 70
p grid[2]
p gridKey points
- Each inner array is one row of the grid.
- The first index picks the row.
- The second index picks the item in that row.
- Two indexes side by side read one cell of the grid.
- One index on its own reads a whole row as an array.
In this example, the grid holds three rows of numbers. The first line reads row 0 at place 2, and that cell holds 6. The first cell of row 2 then changes to 70, and p prints that row before it prints the whole grid.
Note
Each row of a nested array can hold a different count of items.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
The grid is grid = [[1, 2], [3, 4]]. What does puts grid[1][0] print?