Ruby

How to Use Ruby Hashes

Hashes, also called associative arrays, maps, or dictionaries, are data structure types that store data as key-value pairs.

Since hashes store a collection of object references, they tend to behave similarly to arrays. However, unlike arrays, Ruby hashes use any Ruby object type as the index, while arrays use integers.

A Ruby hash has two objects: the index, which we mainly refer to as a key, and the other representing the actual value. Both the key and value of a hash can be of any type.

How to Create a Ruby Hash

As mentioned, hashes follow the format of a dictionary where a key represents a value. An example would be a list of usernames, each pointing to its respective email address.

To create a Ruby hash, enclose the values in a pair of curly braces:

{}

The previously mentioned syntax creates an empty hash with no key-value pairs.

To add data to the hash, we can use the arrow or colon notation. For example, the code below represents valid Ruby Hashes:

{shrek: "[email protected]", leoin: "[email protected]", tropicalne: "[email protected]"}
# Arrow notation
{shrek => "[email protected]", leoin => "[email protected]", tropicalne => "[email protected]"}

Both of the two formats are valid, and Ruby will interpret them as valid Ruby hashes. As you will notice, a comma separates each key-value pair in a hash.

Apart from setting up a hash out of the blue, you can assign the values to a variable as you would for an integer.

For example:

user_db = {shrek: "[email protected]", leoin: "[email protected]", tropicalne: "[email protected]"}
puts user_db

Another way to initialize an empty hash is to use the Hash class. For example:

user_db = Hash.new

Once you have an empty hash initialized, you can assign values using the = sign.

For example:

user_db = Hash.new
user_db["shrek"] = "[email protected]"
user_db["leoin"] = "[email protected]"
user_db["tropicalne"] = "[email protected]"

puts user_db

In the example above, we create an empty hash and assign values to it later.

We pass the hash key inside the square brackets and the target value using the assignment operator.

Running the above code should provide output to all the data in the hash:

{"shrek"=>"[email protected]", "leoin"=>"[email protected]", "tropicalne"=>"[email protected]"}

How to Fetch Array Values

To get a value in a hash, we use a square bracket and pass the target key:

For example:

puts user_db["shrek"]

This should return the value associated with the key–in this case, the email address:

zero@shrek.io

Another way to get a value inside a hash is to use the fetch method. In this case, we pass the target key inside a pair of parentheses.

For example:

puts user_db.fetch("shrek")

Various Ruby Hash Methods

Now, let us look at a few Hash methods you can use to manipulate and work with Hash objects in Ruby:

1. Merge

The first method is the merge method. The merge method allows us to combine two or more hashes to create one hash.

Suppose, we have two hashes of developers and engineers as:

developers = {"Anne": "Python", "Liz": "Ruby on Rails", "Martin": "Java", "Peter": "C++"}
# engineering
engineers = {"Henry": "Chemical Engineer", "Ruby": "Electrical Engineer", "Liam": "Materials Engineer"}

We can combine both hashes to create one hash of employees as:

employees = developers.merge(engineers)
puts employees

This will create one hash, with the key and values of both hashes combined:

{:Anne=>"Python", :Liz=>"Ruby on Rails", :Martin=>"Java", :Peter=>"C++", :Henry=>"Chemical Engineer", :Ruby=>"Electrical Engineer", :Liam=>"Materials Engineer"}

2. Sort

Suppose we want to sort the values in a hash. We can do this by using the sort method. It automatically sorts the values in ascending order.

Here is an example:

developers = {a: "Python", x: "Ruby on Rails", d: "Java", c: "C++"}
puts developers.sort

3. Keys

Also, Ruby provides the keys method that allows you to get the keys available in a hash. For example:

developers = {a: "Python", x: "Ruby on Rails", d: "Java", c: "C++"}
puts developers.keys

The example above will only return the keys of the dictionary and no values:

a
x
d
c

4. Values

If you want to get only the values in the hash, you can use the hash method as:

developers = {a: "Python", x: "Ruby on Rails", d: "Java", c: "C++"}
puts developers.values

The result is only a set of values in the dictionary in the order they appear:

Python
Ruby on Rails
Java
C++

Conclusion

This article was a quick tutorial on how to work with hashes in Ruby. In this, we discussed how to declare a hash, add values, fetch values, and various methods you can use to interact with hashes.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list