- Store multiple pieces of data in on variable using an 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 = 
This is called an empty array.
Alternatively, you could start with items already in your array. Here’s 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. Use the following guided experiments to figure out what is happening with position numbers:
- What name do you expect to be removed by running
names.delete_at(1)? What name is actually deleted?
- Change the position number from
0. What happens?
- What position number would you need to use in order to delete Hanna?
- Change the position number to
9. What happens?
- What can you conclude about position numbers in arrays?
Try It: Arrays
Fork this repl to your own 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? cheesecake ------------------------------ Great! Your favorite foods are: hash browns turkey sandwiches angel hair pasta with red sauce cheesecake Enter the index position of the item you'd like to delete: 1 ------------------------------ Your favorite foods are now: hash browns angel hair pasta with red sauce cheesecake
Challenge #1: 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.
<strongChallenge #2:</strong> Use this example of a concept called "iteration" in order to insert an asterisk (or another symbol of your choice) before each item when they're printed out.