khpeek khpeek - 7 months ago 7
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.merge(more_capitals)

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


I get this result:

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


(see also screen grab from repl.it 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

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:

capitals.merge!(more_capitals)
Comments