6.2 Array Types

6.2.1 One-Dimensional Arrays

An array is an ordered list of variables. To get the idea, imagine a row of compartments, each of the compartments can contain something or be empty, and they are numbered sequentially starting at 0, as you see on the left side of Figure 6-1.

Arrays start counting their elements, or individual variables, at index 0, as the index is the offset from the beginning of the array. Index 0 is the position of the first element in any array that contains at least one element. Likewise, the n th element can be found at index n – 1. Starting at 0 and ending at n – 1 may seem odd, but it is common among most programming languages.

Diagram of an array and array access in Ruby
Figure 6-1. Diagram of an array and array access in Ruby

Gem of Wisdom

Array indices are the offset from the first element. As a result, the first element is stored at index 0.

The arrays in Figure 6-1 are known as one-dimensional arrays because there is only one index or dimension. To access an element in an array in Ruby, the notation is array_name[index], where array_name indicates the name of the array and index indicates the element of the array being referenced.

Consider an array named arr that stores a list of five test scores for a student. The student received the scores 73, 98, 86, 61, and 96. The first step of creating an array is the statement: array_name = Array.new. The example code in Example 6-1 ...

Get Computer Science Programming Basics in Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.