Menu
Coddy logo textTech

Accessing 2D Elements

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 11 of 56.

To read or update a single cell in a 2D array, chain two index lookups: the first picks the row, the second picks the column.

matrix = [
  [10, 20, 30],
  [40, 50, 60],
  [70, 80, 90]
]

puts matrix[0][0]   # 10  (top-left)
puts matrix[1][2]   # 60  (row 1, column 2)
puts matrix[2][0]   # 70  (bottom-left)

Updating a cell uses the same syntax on the left side:

matrix[0][1] = 99
puts matrix[0].inspect   # [10, 99, 30]

Two useful shape queries:

puts matrix.length         # 3 (number of rows)
puts matrix[0].length      # 3 (columns in row 0)

Indexes start at 0 and go up to length - 1. Going past the end returns nil rather than raising an error.

challenge icon

Challenge

Beginner

The 2D array matrix is given. Read three integers (three lines): r1, c1, then v. Then:

  1. Print the value at matrix[r1][c1]
  2. Set matrix[r1][c1] = v
  3. Print the entire updated matrix using inspect

For input 1 / 2 / 99, the output is:

60
[[10, 20, 30], [40, 50, 99], [70, 80, 90]]

Cheat sheet

Access and update cells in a 2D array using chained indexes [row][col]:

matrix = [
  [10, 20, 30],
  [40, 50, 60]
]

puts matrix[1][2]    # 60
matrix[1][2] = 99    # update cell
puts matrix.inspect  # [[10, 20, 30], [40, 50, 99]]

Shape queries:

matrix.length      # number of rows
matrix[0].length   # number of columns in row 0

Indexes start at 0; accessing out-of-bounds returns nil.

Try it yourself

matrix = [
  [10, 20, 30],
  [40, 50, 60],
  [70, 80, 90]
]

r1 = gets.to_i
c1 = gets.to_i
v  = gets.to_i

# TODO: print matrix[r1][c1], assign v, then print the whole matrix
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow