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
BeginnerThe 2D array matrix is given. Read three integers (three lines): r1, c1, then v. Then:
- Print the value at
matrix[r1][c1] - Set
matrix[r1][c1] = v - Print the entire updated
matrixusinginspect
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 0Indexes 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
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