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 Ruby Hashes Hash Methods

Help with Hashes in Ruby

I am unsure about how to hashes in Ruby, and my code isn't working. Can someone please tell me what is the purpose of Hashes in Ruby, and why the code isn't running. Thanks in advance.

hash.rb
grocery_item = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }
calories = { "calories" => 100 }
final_item.merge({'grocery_item.inspect'})
final_item.store({'calories' => 100})

1 Answer

Grace Kelly
Grace Kelly
33,990 Points

Hi Crystal, in order to merge two hashes together we use the merge method. We have a hash called grocery_item and a hash called calories. In order to merge these two we can simply do the following:

grocery_item = { "item" => "Bread", "quantity" => 1, "brand" => "Treehouse Bread Company" }
calories = { "calories" => 100 }
final_item = grocery_item.merge(calories) #merge the calories hash with the grocery_item hash

A hash is a collection of key-value pairs. It's similar to an array but unlike arrays, hashes can have arbitrary objects as indexes ("calories" => 100) while arrays have can only have integers (calories[0] = 100). There's an excellent explanation on hashes here.

Hope that helps!!