Skip to content
AgileLogics
6 min read

Arrays

Prerequisites: Iterators

An array is an ordered list of values.

Real-world analogy: an array is a numbered row of lockers. Each locker holds one item, and you find an item by its locker number.

Syntax

fruits = ["apple", "banana", "cherry"]
empty = []
mixed = [1, "two", :three, nil]

An array can hold values of any type, but in practice one array usually holds one kind of thing.

Reading elements

Positions (called indexes) start at 0:

fruits = ["apple", "banana", "cherry"]

p fruits[0]
p fruits[2]
p fruits[-1]
p fruits[5]
p fruits.first
p fruits.last
p fruits.length
"apple"
"cherry"
"cherry"
nil
"apple"
"cherry"
3

Negative indexes count from the end: -1 is the last element. Reading past the end returns nil rather than raising an error.

Changing an array

fruits = ["apple", "banana"]

fruits << "cherry"        # add to the end
fruits.push("date")       # also adds to the end
fruits.unshift("apricot") # add to the start
fruits[1] = "avocado"     # replace an element
p fruits

removed = fruits.pop      # remove from the end
p removed
fruits.delete("banana")
p fruits
["apricot", "avocado", "banana", "cherry", "date"]
"date"
["apricot", "avocado", "cherry"]

<< (the "shovel" operator) is the most common way to add an element.

A handy shortcut for arrays of words: %w[red green blue] is the same as ["red", "green", "blue"].

Common mistakes

  • Off-by-one errors: the last element of a 3-element array is at index 2, not 3.
  • Not noticing a nil from reading past the end, which then causes a NoMethodError further down.

Practice

Create an array of three cities, add a fourth, then print the first and last cities and the total count.

Show solution
cities = ["Lagos", "Lima", "Oslo"]
cities << "Tokyo"
puts cities.first
puts cities.last
puts cities.length