8. Arrays

Arrays are objects that hold multiple objects. They are somewhat like lists.

In the interactive ruby console, let's type in the following and press enter:

colors = ["red", "blue", "green"]

Now colors holds 3 items, "red", "blue", and "green".

Arrays can be initialized with the [] syntax. To create an empty array, we simply write code like such:

empty_array = []

Another way to declare an empty array is with Array.new.

empty_array = Array.new

Accessing Elements

Let's take a look at the colors array we have just created:

colors = ["red", "blue", "green"]

In the colors array, let's say we want to access the second item, "blue". In order to do this, we simply enter the following code:

colors[1]
=> "blue"

As you can see, you can insert the index of the item next to the variable to retreive the item.

Zero based indexing

But wait, shouldn't it be colors[2]? Since it's the 2nd item, it would make sense to say colors[2] instead of colors[1], right?

Well it turns out that in most computer programming languages, arrays are indexed from 0. That means that the first item would be referenced like colors[0].

We can also replace the element inside of an array:

colors[1]
=> "blue"

colors[1] = "black"
colors
=> ["red", "black", "green"]

Let's make another array. In irb, let's enter the following:

people = ["Jack", "Adam", "Mike"]

Here, we have created a people array with the names of 3 people inside of it. Let's access the first element in the people array. In irb, enter the following:

people[0]

At first, zero based indexing can be a little confusing, but you'll get used to it in no time.

Let's go over some common array methods.

Manipulating the Array

In Ruby, there are a lot of array methods that we can use to manipulate them. Many of them read like English, so they are fairly easy to understand.

Don't worry about trying to memorize everything - the goal here is to simply introduce you to some of the methods that Ruby has. You will remember and internalize these methods once you use them a couple of times - but they are impossible to remember at once.


Let's retrieve the first person in the list. We could access the first person like we just did using indexes:

people[0]

Or, we can use the first method. In irb, type in the following:

people.first


Similarly, to retrieve the last person in the list, simply type the following:

people.last


What if we want to find the size of the array? We can either use count, length, or size. Type the following in irb:

people.count

people.length

people.size

These three methods do the same thing.


To see if an element is inside of an array, we can use the include? method. In irb, type the following code:

people.include?("Jack")

people.include?("Bob")


To get the array index of a certain element, you can use the index method. For example, in our people array, "Jack" is the first element, so the index is 0. In irb, type in the following code:

people.index("Jack")


Sometimes we want to join all elements inside of the array into one whole string. We can use join to accomplish this. Enter the following in irb and see the results:

people.join

As you have probably noticed, the string doesn't look too pretty! All of the names are mushed together. Instead, we want to join all of the names into one string, but put a space between each name. In irb, type in the following code:

people.join(" ")

By passing in a blank space as an argument, we can join the array elements while placing a space in between the elements.


Sometimes we want to remove the last element from the array. For this, we can use the pop method. In irb, type in the following code:

people.pop

If you print out the people array, you will see that the array now only consists of 2 people.


One of the most common operations with arrays is to add a new element into the array. To do this, we can use the push method. In irb, type in the following:

people.push("Bob")

The push method adds the element given in the parameter in the end of the array.

Another way to do the same thing is to use the << syntax.

people << ("Bob")

Which syntax you use is a matter of preference.


To reverse the order of an array, you can use the reverse method:

people.reverse
=> ["Bob", "Adam", "Jack"]


To get a random element form the array, you can use sample:

people.sample


To get only unique elements, you can use uniq:

people = ["Jake", "Jake", "Adam", "Mike", "Mike", "Mike"]

people.uniq


There are a bunch of other array methods that would be great to take a look at. You can take a look at them here<.>

The important thing to remember is that you don't need to memorize all of these methods. In the exercises throughout the course, we will make sure you are reviewing these concepts. You will review these concepts again in the Ruby Core Challenges which you will do before creating your Instagram clone.

Arrays can contain multiple data types

One thing to note is that arrays in Ruby can hold different data types:

array = ["this is a string", 10, 32.12, [true, "Hello"], {key: "value"}]

In other languages, having different types inside an array is not allowed. In Ruby, we have the convenience of allowing multiple types in one array.

Multi-dimensional Arrays

An array can also hold an array within the array.

people = [["Adam", 21], ["Jake", 23], ["Paul", 30]]

Here, we have an array with 3 subarrays inside of it. For example, ["Adam", 21] is one subarray, ["Jake", 23] is another, and ["Paul", 30] is another.

Accessing the data inside multidimensional array can be quite tricky at first. Let's create a multidimensional array that holds the name and age of 3 people:

people = [["Adam", 21], ["Jake", 23], ["Paul", 30]]

# Getting the 0th item will give us the first subarray
people[0]
=> ["Adam", 21]

# To get the first item inside of the subarray, we access the 0th index of the subarray
people[0][0]
=> "Adam"

# To get the second item inside of the subarray, we access the 1st index of the subarray
people[0][1]
=> 21

Overview

Exercise: Super Simple Random Quote Generator

Let's create a super simple random quote generator using arrays in Ruby to get used to working with arrays! Create a new file called quotes.rb.

Inside this file, add the following lines of code:

quotes = Array.new
puts "There are #{quotes.length} quotes now."

quote = "I like Ramen"
puts "Adding #{quote}..."
quotes.push(quote)
puts "There are #{quotes.length} quotes now."

quote = "Momo is good too"
puts "Adding #{quote}..."
quotes.push(quote)
puts "There are #{quotes.length} quotes now."

quote = "I love Ruby"
puts "Adding #{quote}..."
quotes.push(quote)
puts "There are #{quotes.length} quotes now."

quote = "I want to Ruby on Rails"
puts "Adding #{quote}..."
quotes.push(quote)
puts "There are #{quotes.length} quotes now."

quote = "I want to become a web developer"
puts "Adding #{quote}..."
quotes.push(quote)
puts "There are #{quotes.length} quotes now."

puts "....."
puts "Generating random quote......"
puts "....."

random_quote = quotes.sample

puts "Random quote at index #{quotes.index(random_quote)}: #{random_quote}"

Save the file and run the program.

Your output should look like this:

There are 0 quotes now.
Adding I like Ramen...
There are 1 quotes now.
Adding Momo is good too...
There are 2 quotes now.
Adding I love Ruby...
There are 3 quotes now.
Adding I want to Ruby on Rails...
There are 4 quotes now.
Adding I want to become a web developer...
There are 5 quotes now.
.....
Generating random quote......
.....
Random quote at index 4: I want to become a web developer

You will notice that every time you run the code, the quote generated will be random.

Assignment