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

Brian Sylvester
Brian Sylvester
2,010 Points

Clarification on the merge method (as taught in the Hash Methods video)

In this video, Jason used the merge method to merge the original hash with {'calories' => 100}". He explained how it returns the hash with the new key added, but "if we look back at that original hash, it does not have the calories key. This is because merge will create a new hash."

I'm slightly confused about what is going on when merge is "creating a new hash." How would I print that new hash later on in the code, if I hypothetically wanted to do that? Or, is it only creating a new hash on the spot after the merge method is called?

Hope that makes sense!

1 Answer

Kourosh Raeen
Kourosh Raeen
23,733 Points

Hi Brian - You can just store what merge returns in a new variable:

new_hash = hash.merge({'calories' => 100})

And if later on you want to print it you can:

puts new_hash

Also, if you just want to modify the original hash and not return a new one you can use merge!:

hash.merge!({'calories' => 100})

You can now inspect the original hash and you'll see that it is changed.

Brian Sylvester
Brian Sylvester
2,010 Points

Thank you for the thorough response Kourosh! That makes sense.

Kourosh Raeen
Kourosh Raeen
23,733 Points

My pleasure! Happy coding!