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
endThis style is shorter and safer than tracking indexes by hand, there's no risk of going past the end of a row.
Challenge
EasyThe 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) = valueUse 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) = 7Cheat 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
endTo 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
endTry it yourself
grid = [
[1, 8, 3],
[4, 5, 9],
[6, 7, 2]
]
# TODO: nested each_with_index, print cells > the row's average
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier32D Arrays
2D Array BasicsAccessing 2D ElementsIterating Over 2D ArraysCommon 2D PatternsRecap - Matrix Operations