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

Nick Vitsinsky
Nick Vitsinsky
7,246 Points

Why is my solution wrong\bad?

Add the grocery_item hash to the items array inside of the grocery_list hash.

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

my solution

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

solution that I found when I was in doubt that mine is proper

grocery_list = { 'title' => 'Grocery List', 'items' => [] }
grocery_item = { 'title' => 'Bread', 'quantity' => 1 }
grocery_list['items'].push(grocery_item)

The question is - why my solution is bad or wrong? Or it's just differs?

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

1 Answer

Martin Cornejo Saavedra
Martin Cornejo Saavedra
18,132 Points

The result of your solution and the .push solution is the same, but your way is less 'elegant', because you are asigning again the grocery_list variable, on the other side the 'good' solution just modifies the variable, pushing a hash inside the 'items' array.

What if 'item' weren't an empty array? Then your solution could not work because you could be overwriting content. push is a nice solution because you just add an item to the array, without deleting previous content.