Creating and accessing arrays

Free preview 3 min to read

An array holds many values in one variable

Every value so far, a number, a string or a boolean, lived alone in its own variable. An array holds an ordered list of values behind one name.

fruits = ["apple", "banana", "cherry"]
scores = [88, 95, 72, 100]
mixed = ["Ada", 36, true]
empty = []

Square brackets, [...], are the array literal. Commas separate the elements, and one array can mix types: mixed holds a string, an integer and a boolean.

Each element has a position

Ruby numbers positions from 0, not 1. That trips up nearly everyone at first: the first element is at index 0, the second at 1, and so on.

fruits = ["apple", "banana", "cherry"]
fruits[0]   # => "apple"
fruits[1]   # => "banana"
fruits[2]   # => "cherry"
fruits[3]   # => nil, there is no fourth element

Reading past the end doesn't raise an error; it returns nil. It's the same quiet nil you saw for unset instance variables in Ruby variables & assignment.

Negative indices count from the end

Negative indices count backward from the last element.

fruits = ["apple", "banana", "cherry"]
fruits[-1]   # => "cherry", the last element
fruits[-2]   # => "banana", the second-to-last
fruits[-10]  # => nil, still out of bounds, just from the other direction

fruits[-1] for "the last element" is everywhere in real code. It reads better than computing fruits[fruits.length - 1].

first, last, length, and size

Four methods answer the common questions without an index.

fruits = ["apple", "banana", "cherry"]
fruits.first    # => "apple"
fruits.last     # => "cherry"
fruits.length   # => 3
fruits.size     # => 3, an exact alias for length

On an Array, length and size are two names for one method, so either works. size is the more common in practice: this app's own code and Rails' source both use it about twice as often as length.

One caveat for later, since this series heads to Rails. They're aliases on an Array, but not everywhere. On an ActiveRecord relation, size uses an already-loaded count or runs a COUNT(*) query, while length loads every record into memory to count them. On a plain array it can't matter, but it's a good habit to form now.

Key takeaways

  • An array literal is written with square brackets and comma-separated values: [1, 2, 3].
  • Elements are indexed starting at 0, not 1; reading past the end returns nil rather than raising an error.
  • Negative indices count backward from the end: -1 is the last element, -2 is second-to-last.
  • first and last read the ends without computing an index; length and size are exact aliases on an Array: but not on an ActiveRecord relation, where size counts and length loads.
Lesson 1 of 7 · free

Keep going with lesson 2

Adding and removing elements

Adding and removing elements at both ends with push, <<, pop, unshift and shift, all of which mutate the array.

A free account also gives you the quizzes, your progress and notes, and the discussion.

Type to start searching...