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 trial

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

Tyler Proctor
Tyler Proctor
11,458 Points

I've tried this so many ways. Can someone provide the answer and an explanation of why it needs to be done that way?

I've done a lot of googling and external research and i understand how to merge two hashes, but how do I merge one hash to a particular key within a hash? I've tried grocery_list.merge(grocery_item), grocery_list.items[].merge(grocery_item), items[].merge(grocery_item), {"items" => []}.merge(grocery_item), etc. I feel like i've got to be close, but can't quite get it.

1 Answer

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

SO basically, for this challenge, there're 2 steps here. First, you need to access the grocery_list Hash for the value associated w/ the items key, that value is an empty array by the way; Second step is to push the grocery_item Hash into the end of this Array.

There're many ways to accomplish this task, here're two.

grocery_list['items'].push(grocery_item)  # by using the .push() method
grocery_list['items'] << grocery_item  # by using the << notation.

Hope it helps.