Lesson Monday

Another built-in Ruby class designed for storing data is the Hash class. Elements in a hash are stored in key-value pairs made of a key and a value. Let's build a new hash to demonstrate.

We'll make a Hash object that stores contact information like a phone book with the contact name as the key and the phone number as its matching value.

> phonebook = Hash.new()
> phonebook.store("Michael", 5035551212)
> phonebook.store("Li", 4159990000)
> phonebook.store("Juan Carlo", 2021115599)
> phonebook.fetch("Michael")
=> 5035551212
> phonebook.fetch("Li")
=> 4159990000

The Hash class has a store() method for adding elements to a hash. The first argument to Hash#store is the key, and the second is the value. It also has a fetch() method which takes the key as an argument and returns its matching value.

Let's look at another example where our Hash is a dictionary with words as keys and definitions as values.

> dictionary = Hash.new()
> dictionary.store("fish", "underwater animal")
> dictionary.store("shoes", "clothes for your feet")
> dictionary.store("rain", "water from the sky")
> dictionary.fetch("shoes")
=> "clothes for your feet"
> dictionary.fetch("fish")
=> "underwater animal"

Hashes also have a literal notation which is more frequently used. New hashes can be created by using curly braces and key-value pairs separated by commas.

> numbers = { "Michael" => 5035551212, "Li" => 4159990000, "Juan Carlo" => 2021115599 }
> numbers.fetch("Michael")
=> 5035551212

Here are some other frequently used methods for hashes:

include?(key) # returns true if the key is present in the hash
invert() # returns a new hash using the values as keys, and the keys as values
key(value) # returns the key corresponding to the given value
keys() # returns an array of all the keys
length() # returns the number of entries.
merge(other_hash) # combines two hashes into one


The following creates a Hash object to store contact information like a phone book:

> phonebook = Hash.new()
> phonebook.store("michael", 5035551212)
> phonebook.store("jessica", 4159990000)
> phonebook.store("chris", 2021115599)
> phonebook.fetch("michael")
=> 5035551212
> phonebook.fetch("jessica")
=> 4159990000
  • phonebook is a Hash, created with .new().
  • When we say phonebook.store("michael", 5035551212), we are creating a new key-value pair.
  • In the Hash entry mentioned above, "michael" is the key and 5035551212 is the value.

Lesson 7 of 22
Last updated August 7, 2022