Back to Curriculum Index


  • Store multiple pieces of data in on variable using an array
  • Understand the purpose and use-case for arrays in real-world applications

The Array

An array is like a box you can use to contain multiple things, such as strings or integers. In programming, we declare an array like this:

names = ["Kenny", "Marisol", "Ruben", "Hanna"]

The previous example shows a variable that stores an array of strings.

You can also add items to your array using the “shovel” syntax, like so:

Finally, you can use the method delete_at() to remove an item from the array. Fork this and use the following guided experiments to figure out what is happening with position numbers:

  1. What name do you expect to be removed by running names.delete_at(1)? What name is actually deleted?
  2. Change the position number from 1 to 0. What happens?
  3. What position number would you need to use in order to delete Hanna?
  4. Change the position number to 9. What happens?
  5. What can you conclude about position numbers in arrays?

Try It: Arrays

Fork this to your account.

Part 1: Add code to make it so that the program asks the user for their favorite breakfast food, favorite lunch food, favorite dinner food, and favorite dessert. Once you have those items, print them out for the user.

Part 2: Add one more question that asks the user to enter the INDEX POSITION of the item they'd like to delete. Note that when you get the user's input, you'll need to use gets.chomp.to_i in order to use the input as a number instead of a string. Then delete that from your array and re-print their foods list.

This is an example of how your program should function:

What is your favorite breakfast food?
hash browns
What is your favorite lunch food?
turkey sandwiches
What is your favorite dinner food?
angel hair pasta
What is your favorite dessert?
Great! Your favorite foods are:
hash browns
turkey sandwiches
angel hair pasta
Enter the index position of the item you'd like to delete:
Your favorite foods are now:
hash browns
angel hair pasta

🌶Click here for a Spicy Challenge🌶

It's not very intuitive for a user to enter "0" to delete the first item in their list. Can you modify the user's input number to match with how they probably expect the program to function? This means that if they enter "1", your program should delete the very first item in the list, not the second item.

Next: Iteration