khpeek khpeek - 2 years ago 76
Ruby Question

Merging hashes in Ruby not working as intended

I'm trying to reproduce an example in a Ruby tutorial of merging two hashes. However, using the "merge" method does not have the desired effect. When I run the following script:

capitals={'New York' => 'Albany','California' => 'Sacramento'}
more_capitals={'Texas' => 'Austin', 'Alaska' => 'Fairbanks'}


capitals.each do |state,capital|
puts "#{capital} is the capital of #{state}"

I get this result:

Albany is the capital of New York
Sacramento is the capital of California

(see also screen grab from below). I would however also expect the output to contain "Austin is the capital of Texas" and "Fairbanks is the capital of Alaska" if the merging of the "capitals" and "more_capitals" hashes were carried out correctly. Why is this not the case?

enter image description here

Answer Source

You're using the non-destructive version of merge, which returns a new Hash you need to assign and use.

new_capitals = capitals.merge(more_capitals)

Or, you can use merge!, which does it in place:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download