Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialEva Pradhan
6,907 PointsNote 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.
grocery_list = { 'title' => 'Grocery List', 'items' => [] }
grocery_item = { 'title' => 'Bread', 'quantity' => 1 }
4 Answers
Umar Ghouse
14,607 PointsOK, 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
6,907 PointsThanks a lot, it was a great help. Thank you once again. Really Appreciate your help.
Lena SURLENET
972 PointsI am 2 years late but : This is an awesome explanation ! Thank you very much :)
K .
2,357 Pointswow, 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.