CodeNewbie Community 🌱

Cover image for 49 Days of Ruby: Day 9 - Arrays
Ben Greenberg
Ben Greenberg

Posted on • Originally published at on

49 Days of Ruby: Day 9 - Arrays

Welcome to day 9 of the 49 Days of Ruby! 🎉

Today is all about another important data type, the array!

Arrays are one of the most common data types you will use from your Ruby toolkit. They serve all kinds of purposes and are a general use structure to hold information.

What exactly is an Array?

An array is an ordered indexed collection of data.

That sounds nice, but how does it work? It is best to see with an example:

coffees = ["espresso", "americano"]


# => "espresso"


# => "americano"

Enter fullscreen mode Exit fullscreen mode

In the above example, we created a new array called coffees and put two types of coffee in it; espresso and americano

In order to retrieve the coffee types we added into our array we need to access them by their index number: The first item starts at index 0.

Thus, to get our espresso, we do: coffees[0]. To access our americano, we do: coffees[1]. The item at index number 1 is the second item in the array.

Experiment With Arrays

Now it's time for you to experiment with arrays!

In order to do so, we're going to learn about iteration and demonstrate one method to iterate with. Iteration is when you access each item in a collection and do something with it.

The #each method in Ruby is a popular and often used way to iterate over a data collection. This is how it works:

coffees = ["espresso", "americano"]

coffees.each |coffee|
  puts "Today, I will have an #{coffee}"

# => "Today, I will have an espresso"
# => "Today, I will have an americano"

Enter fullscreen mode Exit fullscreen mode

We learned previously about string interpolation, which is where you combine a string of text with a variable, and the data in the variable is used inside the string.

In this case, we are using string interpolation and iteration together to construct a new sentence for each value inside our coffees array.

Your task today is to open up IRB on your computer and experiment with arrays and the #each method. What can you do? What ideas from the previous lessons can you combine with these new skills? Share them on Twitter with hashtag #49daysofruby!

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Top comments (0)