This chapter will be a deep dive into arrays in Ruby. Arrays are a great way to combine strings and numbers together into one data type that resembles a list.
You've also seen arrays already in this course! Think back to a person's
outfitattribute from part 1:
person.outfit = ["red shirt", "blue jeans", "white shoes"]
The list of items in the outfit is an array.
Arrays are delineated by square brackets and can contain almost any type of data inside in list format. Each element must be separated by a comma.
All of the following are valid arrays:
# Array full of numbers [1, 2, 3, 4, 5, 10] # Array full of strings ["apple", "orange", "pear"] # Array full of numbers and strings [1, "two", 3, "four"] # Array full of numbers, strings, and arrays [1, "two", [3, 4, 5], "six", 7]
That last one is pretty nuts!
Accessing elements within arrays
Arrays become particularly useful when you can access individual elements in them. For example, if you have a list of users who just signed up, you might want to access the first user in the list in order to send them an early-bird newsletter.
In order to access elements in arrays, you'll need to use what's called an index. An index is used to specify exactly which element you want.
Take the following array as an example:
fruits = ["apple", "pear", "orange"]
If I want to access "apple" in the above array, I want the item that's at position 1, right? Not exactly, it turns out. In array-land, this is kind-of tricky. Why?
👉 An array index always starts at 0. 👈
This means that, even though "apple" is first in the list, it's technically at position 0 according to Ruby.
This can be visualized in the following way (I've added a few extra fruits):
To access an element at a certain position, pass the number of the index in square brackets to the name of the array.
fruits = ["apple", "pear", "orange"] => ["apple", "pear", "orange"] fruits => "apple"
By passing an index of 0 to the
fruitsarray, I have a return value of
"apple". In order to access
"pear", I'd type
fruits. For "orange", I'd type
Play in the interactive code exercise below in order to see how to create and access content in arrays.
Bonus challenge: adding content to arrays
Arrays are rarely static entities that have the same content in them all the time. For example, an array of users is likely to grow and grow as more users get added to it.
While you don't have the means to practice on this type of behavior in a real code base for the moment, you'll see arrays that change all the time once you start working on live Ruby code bases.
That's why it's important to know how to append content to arrays, meaning add additional items to a list. Check out how to do so in the screencast below.
Bonus challenge: prepending content to arrays
You may also want to prepend content to arrays, meaning add elements to the beginning of your array list. Check out this screencast on how to do so (hint: it's not so different from appending items)!