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

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,857 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.