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

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.