Working with Ruby Arrays

Hi there!

Most of the time, we’ll be working with collections of things. In Ruby, these collections are called arrays. Today we’ll be working with arrays and perform some basic operations to help everyone get started. Don’t worry! It’s not that hard to work with Ruby arrays.

I’ll provide a simple example of this powerful tool by marrying one of the things I love the most – Japanese cuisine. We’ll create our own chirashi. It’s basically a big bowl of rice with various ingredients.

On this chirashi, we’ll add the following ingredients: Uni (Sea Urchin), Maguro (Tuna) and Hamachi (Pacific Yellowtail).

Screen Shot 2016-01-01 at 11.50.39 PM

 

Step # 1: Create an array (or the chirashi) with 3 elements (or ingredients). Take note that “Uni” is at index 0, “Maguro” is at index 1, and “Hamachi” is at index 2. If this confuses you, just remember that counting starts at zero in Ruby arrays.

chirashi = [“Uni”, “Maguro”, “Hamachi”]

 

Step # 2: What is the first element that we added to the array? To print the first element of the array, you can access it by adding [0] to the name of the array since “Uni” is at index 0

puts chirashi[0]

=> Uni

 

Step # 3: Print the second element of the array. Since “Maguro” is at index 1, you can access it by adding [1] to the name of the array

puts chirashi[1]

=> Maguro

 

Step # 4: Oh, I changed my mind. I wanted to add Tamago (Egg) too. In this case, if we wanted to add another item to the array, we can use push to append the new element.

chirashi.push(“Tamago”)

=> [“Uni”, “Maguro”, “Hamachi”, “Tamago”]

 

Step # 5: What was the latest item we added into the array again? To print the fourth element of the array, remember that the index is 3 for the fourth item as seen below.

puts chirashi[3]

=> Tamago

 

It’s that easy! Most of the time, we’ll just be creating arrays and appending to existing ones so this should help you get started.

Stay tuned for more!

Leave a Reply

Your email address will not be published. Required fields are marked *