Menu
Coddy logo textTech

Iterating Over 2D Arrays

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

To visit every cell in a 2D array, you nest two iterations. The outer loop walks through rows; the inner loop walks through that row's columns.

The most idiomatic Ruby pattern uses each twice:

grid = [
  [1, 2, 3],
  [4, 5, 6]
]

grid.each do |row|
  row.each do |cell|
    puts cell
  end
end
# 1, 2, 3, 4, 5, 6  (each on its own line)

If you also need the row and column indexes, for example to label each cell, use each_with_index at both levels:

grid.each_with_index do |row, r|
  row.each_with_index do |cell, c|
    puts "(#{r},#{c}) = #{cell}"
  end
end

This style is shorter and safer than tracking indexes by hand, there's no risk of going past the end of a row.

challenge icon

Challenge

Easy

The 2D array grid is given (3 rows × 3 columns of integers).

For each row, find every cell whose value is strictly greater than that row's average. Print each such cell on its own line in the format:

(r,c) = value

Use nested each_with_index. Compute the average inside the outer loop so each row's threshold is independent.

For the default grid, the cells that beat their row's average are:

(0,1) = 8
(1,2) = 9
(2,0) = 6
(2,1) = 7

Cheat sheet

To iterate over every cell in a 2D array, nest two each calls:

grid.each do |row|
  row.each do |cell|
    puts cell
  end
end

To also access row and column indexes, use each_with_index at both levels:

grid.each_with_index do |row, r|
  row.each_with_index do |cell, c|
    puts "(#{r},#{c}) = #{cell}"
  end
end

Try it yourself

grid = [
  [1, 8, 3],
  [4, 5, 9],
  [6, 7, 2]
]

# TODO: nested each_with_index, print cells > the row's average
quiz iconTest yourself

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

All lessons in Logic & Flow