Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby Ruby Collections Build a Grocery List Program Working with Hashes That Contain Arrays

Eva Pradhan
Eva Pradhan
6,907 Points

Note sure with this challenge

Let's add an item to our grocery list. We've set up a grocery_list hash that has an 'items' key with an empty array as its value. We've also created another hash and stored it in the grocery_item variable. Append the grocery_item hash to the empty array that's under the grocery_list hash's 'items' key.

shopping_list.rb
grocery_list = { 'title' => 'Grocery List', 'items' => [] }
grocery_item = { 'title' => 'Bread', 'quantity' => 1 }

4 Answers

Umar Ghouse
Umar Ghouse
14,607 Points

OK, so let's break this down. Basically, you have 2 hashes. One hash contains information about a grocery item (i.e. just one item that you want to buy). The other hash contains information on the entire grocery list.

The grocery list hash has an "items" key - this is an array that contains all the grocery items that you want to buy.

What can be confusing here is the structure. So, if we put it out in words, we can say that the grocery_list variable has an "items" key. The value of the "items" key is an array. That array is going to have a collection of hashes (each hash corresponds to a grocery_item variable). i.e. the "items" array is an array of hashes

To access the "items" key in the grocery_list variable, we do:

grocery_list["items"]
# For now, this returns an empty array, i.e. []

That will show us all the items in the grocery list. Remember, this value is an array. So, we can use array methods to append the grocery_item hash to this array, like so:

grocery_list["items"] << grocery_item
# The << symbol is ruby shorthand for appending values to an array.

I hope that helped! Let me know if you have any questions :)

Eva Pradhan
Eva Pradhan
6,907 Points

Thanks a lot, it was a great help. Thank you once again. Really Appreciate your help.

I am 2 years late but : This is an awesome explanation ! Thank you very much :)

wow, the answer was so simple. I was overthinking it. I created a whole new variable to create an empty array. I then tried to append the grocery_item hash to the new empty array lol smh.