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

Yuichi Narisawa
Yuichi Narisawa
19,548 Points

How can I add a hash to another hash?

I thought I just need to pipe in the name of hash, but it didn't work. it looks quite silly question, but I need help!

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

1 Answer

Hi Yuichi,

In the original code, the "items" key in the grocery_list hash is an array.

So you have to add the grocery_item hash to that array.

One way to do that is push it onto the array.

grocery_list['items'].push grocery_item
Yuichi Narisawa
Yuichi Narisawa
19,548 Points

Hi Jason, Thank you for the answer! I've just followed your guide and tried some codes, but still no luck... Could you check my code again?

grocery_list = { 'title' => 'Grocery List', 'items' => 'grocery_item' }

grocery_list['items'] << 'grocery_item'

grocery_item = { 'title' => 'Bread', 'quantity' => 1 }

I thought it should add "grocery_item" hash to "items" array in "grocery_list".

One more question. What's the difference between ' and " ? Does the single quotation mean variable and double quotation mean mere string? Am I right?

I feel myself so dummy that I cannot write even a simple code!

You don't want to change the starter code. The 'items' key is supposed to be an empty array on the first line.

You want to add your code after those first 2 lines.

The way you did it could work but you're pushing the string 'grocery_item' onto the array and not the variable.

Try it like this without the quotes around grocery_item

grocery_list['items'] << grocery_item

and make sure that you put it after the 2 lines you start with. You can't use grocery_item before it's defined.

Both single and double quotes will create strings. The main difference seems to be that with double quotes you can do string interpolation and you can escape characters.

You can see this stackoverflow link for more detailed info: http://stackoverflow.com/questions/6395288/double-vs-single-quotes

Yuichi Narisawa
Yuichi Narisawa
19,548 Points

Jason,

Thank you for your quick response, and detailed answer! I could finally understand it! Thank you sooo much!