Things We Can Do with Hashes

Practice calling some important methods on hashes.

Methods of the Hash class

The main purpose of a Hash object is to look a value up by a key. However, there are a few more things we can do with hashes. Below is a list of methods supported by the Hash class. Don’t be too concerned with memorizing all of them.

The merge method

We can merge two hashes by calling the merge method:

Press + to interact
dictionary={ "one" => "eins" }.merge({ "two" => "zwei" })
puts dictionary

The fetch method

The fetch method does just the same as the square bracket lookup ([]) discussed before, but it raises an error if the key isn’t defined:

Press + to interact
dictionary = { "one" => "eins" }
puts dictionary.fetch("one")
puts dictionary.fetch("two")

Notice that line 2 outputs “eins”, but line 3 raises an error.

The keys method

The keys method returns an array with all the keys that the hash knows:

Press + to interact
dictionary = { "one" => "eins", "two" => "zwei" }
puts dictionary.keys

The length and size methods

The length and size methods both indicate the number of key/value pairs contained in the hash:

Press + to interact
dictionary = { "one" => "eins", "two" => "zwei" }
puts dictionary.length
puts dictionary.size