O'Reilly logo

Learning Ruby by Michael Fitzgerald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Changing Hashes

Hash's []= method replaces or adds key-value pairs to an existing hash. For example:

rhode_island = { 1 => "Bristol", 2 => "Kent", 3 => "Newport", 4 => "Providence",
5 => "Washington" }

By the way, this hash uses integers as keys, similar to the way an array is indexed, but it doesn't use 0, which is the first index of an array.

You can use []= to add a pair to this array:

rhode_island[6]= "Dunthorpe"

This adds the value "Dunthorpe" with a key 6. Or you can use []= to change a value:

rhode_island[2]= "Bent"

This changes the value associated with the key 2 to "Bent". Similarly, you can use the store method to add a pair to the rhode_island array:

rhode_island.store(6, "Dunthorpe")

Merging Hashes

In addition to rhode_island, you also have a hash listing the counties in Delaware. There are only three:

delaware = { 1 => "Kent", 2 => "New Castle", 3 => "Sussex" }

Look again at the Rhode Island hash:

rhode_island = { 1 => "Bristol", 2 => "Kent", 3 => "Newport", 4 => "Providence",
5 => "Washington" }

The merge method merges two hashes together, producing a copy of the hashes that removes duplicate keys by overwriting the key-value pairs from the merged array. To see what I mean by all that, run the example:

rhode_island.merge delaware # => {5=>"Washington",
1=>"Kent", 2=>"New Castle", 3=>"Sussex", 4=>"Providence"}

Do you see what happened in the result? The keys and values from delaware took over the pairs with the same keys in rhode_island, making Bristol, Kent, and Newport disappear. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required