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

Daniel Hulin
Daniel Hulin
1,852 Points

What is wrong with my setup when combining my hashes?

I tried to combine the calories to the grocery_list. Then that to the final hash. hat do I need to do?

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

final_item = {}
final_item.merge!(grocery_item)

1 Answer

Hi Daniel,

You have written the correct line, you just didn't assign it to final_item.

Try this;

final_item = grocery_item.merge(calories)

So you call the merge method on one of the hashes and pass in the other hash. This then needs to be assigned to the new hash name.

You'd done that in your code!

Steve.

Daniel Hulin
Daniel Hulin
1,852 Points

Thanks! I understand what you did, but is there a way to merge like I was tring to do? EX: final_item.merge(grocery_item, calories)

Not with the merge method as that is expecting only one argument. This won't work:

final_item = {}
final_item.merge(grocery_item, calories)

Also, I think you still need to assign the new value. So, the merge doesn't alter either hash, perhaps, but returns the altered/combined hash for you to handle how you choose.

So, here, other_item holds the same after the merge; but the assignment stores the merged hash into new_hash.

other_item = {name: "Bread", quantity: 1}
new_hash = other_item.merge(item)
puts other_item.inspect # just the same as at the beginning
puts new_hash.inspect

There may be alternative methods to use to add hashes together; but merge seems to want one parameter and its result will need assigning, if only to the original hash, for example. You could do this twice:

final_item = final_item.merge(calories)
final_item = final_item.merge(grocery_item)

Maybe this can be chained?

final_item = (final_item.merge(calories)).merge(grocery_item) # doesn't work

But that's not really adding much the more simple:

final_item = grocery_list.merge(calories)

Steve.