Working with Arrays
Learn about arrays and how to operate on them in Ruby.
Defining arrays
While numbers, strings, true
, false
, and nil
all represent simple, primitive things, Array
objects (arrays) are more interesting and very useful.
Arrays are things that store other things. Think of an array as a list of things, or a special type of bag that we can throw things in. The bag itself is a thing (object) too.
Remember: An array is an object that stores other objects.
An array is created by separating values by commas and enclosing the list with square brackets, like so:
[1, 2, 3]
This is a simple array that holds three numbers.
Note that elements in arrays always retain their order. Unlike elements in a real bag, which get shuffled around, an array always keeps its objects in the same defined order, unless we do something to change the order.
Arrays can contain all kinds of things:
["A string", 1, true, :symbol, 2]
This creates an array with five elements. These are a string, a number, true
, a symbol, and another number.
For example, we can also store arrays in an array. This is a two-dimensional array, like a table that has many rows, where each row has many cells.
This is quite common to use when we need to represent some data with the characteristics of a table, like a spreadsheet.
In the following example, the outer array represents the table, and each inner array represents one row. Each value then represents a cell. The following is an example of a two-dimensional or nested, array that represents the structure of number keys on a phone.:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]
We’ll revisit nested arrays later in the course.
Remember: Arrays have a defined order and can store all kinds of objects.
Retrieving an element from an array
Arrays can be used in a lot of different and useful ways, but the most basic is to retrieve a certain element by referring to its position. Please get me the element at position 1
, we might say.
In Ruby, we can do this with square brackets, like so:
words = ["one", "two", "three"]puts words[1]
Notice how we use a variable to assign a name to our array here.
The words[1]
phrase retrieves the element at position 1
from the words
array. The puts command then prints this value out to the screen. (puts
stands for “(out)puts the string.”)
Clicking on “Run” above likely doesn’t produce the expected value one
.
This is because the first position in an array is 0
, not 1
. So, 1
refers to the second element, not the first.
In programming books and the Ruby documentation, index is often used instead of position in this context. It’s also helpful to know that the plural of the index is indexes.
Remember: Arrays start with the index
0
, not1
.
Notice that square brackets ([]
) mean different things when used in different contexts. The same is true for other punctuation.
In our case here:
- The square brackets on the first line are used to create an
Array
object with the given elements (assigned to thewords
variable). - On the second line, the square brackets are appended to the variable name,
words
. This means we want to look an element up from the array calledwords
.
Remember: Punctuation (such as square brackets) has different meanings in different contexts.
The first
and last
methods are alternative ways to retrieve the first and last elements:
puts [1, 2, 3].firstputs [1, 2, 3].last
Missing elements
What if we try to retrieve an element that doesn’t exist, say the element at the fourth or fifth position (index)?
We get back nil
, meaning nothing:
words = ["one", "two", "three"]puts words[3]puts words[4]
Appending an element to an array
In order to add an element to the end of an existing array, we can use the shovel operator (<<
), like so:
words = ["one", "two", "three"]words << "four"puts words[3]
This prints out four
. The string four
is shoveled into or appended to, the array. Because it now sits at position 3
, we can access it using words[3]
.
Setting an element to a position
We can also set an element to a specific index, like so:
words = ["one", "two", "three"]words[3] = "four"puts words[3]
This also prints out four
.
We could also overwrite existing elements the same way. For example, this sets the word "uno"
to the position 0
(overwriting "one"
):
words = ["one", "two", "three"]words[0] = "uno"puts words[0]
So, this would now output uno
.
Note: There are no spaces inside the square brackets, and there’s one space after each comma.