Menu
Coddy logo textTech

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 zeros

The 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 icon

Challenge

Easy

Read 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 zeros

Try it yourself

rows = gets.to_i
cols = gets.to_i

# TODO: build the grid and print it with inspect
quiz iconTest yourself

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

All lessons in Logic & Flow