2D Array Basics
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 10 of 56.
A 2D array is an array whose elements are themselves arrays. Each inner array represents a row in a grid.
cinema = [
[true, true], # Row 0
[false, true] # Row 1
]This represents a 2×2 grid, two rows, each with two columns.
To create a 3×4 grid of integers:
matrix = [
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]
]You can build a grid filled with a default value using Array.new twice, once for rows, once for columns:
grid = Array.new(3) { Array.new(4, 0) }
# 3 rows, 4 columns, all zerosThe block form ({ Array.new(4, 0) }) matters, it creates a fresh inner array for each row. Without it, every row would point at the same array.
Challenge
EasyRead two integers (two lines of input): rows and cols. Build a 2D array of that size where every cell equals row * cols + col + 1 (so the first row counts from 1, and the grid fills in reading order).
Print the grid using inspect on the outer array, one line.
For input 2 then 3, the output is:
[[1, 2, 3], [4, 5, 6]]Cheat sheet
2D arrays are arrays of arrays, where each inner array is a row:
matrix = [
[1, 2, 3],
[4, 5, 6]
]Build a grid with a default value using Array.new with a block (block ensures each row is a separate array):
grid = Array.new(3) { Array.new(4, 0) }
# 3 rows, 4 columns, all zerosTry it yourself
rows = gets.to_i
cols = gets.to_i
# TODO: build the grid and print it with inspect
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