Ruby: Intro to Hashes

Ines Guerrero
8 min readMay 19, 2019

--

In Ruby: Intro to Arrays Part 1, I gave a brief intro to arrays using a BBQ as an example. Here, I’ll continue with the BBQ to explain how to iterate over an array and make a hash with the same values. If you want to read Part 1, click here.

Going back to arrays for a moment, we can see that our BBQ list (which I’ve updated) contains every single item that we need to feed our vegan, vegetarian, gluten-free, and meat-eating friends.

1. Array: BBQ meal

Wow! We can’t take that into the grocery store. I don’t know about you but I’m already confused. What I would like to see is the item followed by the quantity. Something like this:

2. BBQ meal hash

Now, that looks a lot better, doesn’t it?

Before we discuss how to convert our bbq_meal array into a hash, let’s go back to basics.

Intro to Hashes

Hashes store data using key-value pairs. Unlike arrays, which store a list of items, hashes store data in an associated manner. Hashes work like dictionaries. Imagine you want to find out the meaning of a word. The word would be the key in a hash, and its meaning would be the value. So, you would look for the value, using the key.

Creating a hash

Each key-value pair is one unit of the hash. As we saw in Image 2, you can create a hash by enclosing everything in curly braces {}, assigning values to keys with a “ =>”, known in the Ruby community as a hash rocket, and separating units with a comma ( , ).

There are two ways to create a hash, the literal constructor and the class constructor. The literal constructor allows us to initialize a hash with data in it, just like with arrays.

3. A hash with 3 units (3 key-value pairs) created using the literal constructor

You can also create a hash using the class constructor, found below:

4. Creating a hash with the class constructor

Hashes can be written in different ways. For example, using symbols as keys:

5. A hash with symbols as keys

Up until a few years ago, the only way to create hashes was by using the hash rocket, however, a new syntax was later introduced using only symbols:

6. Hash without hash rockets

All of these are hashes that represent the same things. Symbols are beneficial because they are immutable, which means that they cannot be modified after they are created so, they use up less memory. However, we will write hashes as the first example, as this is more explicit and easier to understand for beginners.

Looking up a value

In Part 1, we saw that each value of an array has an index number. We were able to call on this value by using its index number. In a hash, we use the key to retrieve the value. We can do this using the bracket method.

Taking our hash_example hash, we will get the value of the first_key by writing the name of the hash and then the name of the key in brackets:

hash_example[“first_key”]

7. Retrieving a value using the bracket method

Adding a value to a hash

Instead of the shovel method (used in arrays), we use the bracket-equals method to add key-value pairs to hashes. To add a fourth key-value pair to our hash, we would write the name of the hash followed by the name of the new key in brackets and equal that to the new value:

hash_example[“fourth_key”] = “fourth_value”

8. Adding a key-value pair to a hash

Keys and values

In hashes, you can use any kind of objects for the key and/or the value. Let’s go back to our BBQ example. We would like to know how many beef patties we need. In this case, we would like to assign an integer to the value of the beef patty key, like this:

9. Assigning an integer as the value of a key in a hash

Common methods

Merging hashes

Let’s say we have some items in our bbq_meal hash and we want to add one more key-value pair. In this case, we would use the bracket-equals method. However, what if we are missing a lot of items? Do we want to re-write the entire hash? Umm.. no. We could create a second hash with all the missing items and then merge both hashes. Let’s take a look.

Our first hash would have some items:

10. Incomplete bbq hash

Our second hash has the missing items:

11. BBQ hash with missing items

Instead of re-writing either of the hashes, we will merge them into our bbq_meal hash by writing the following:

bbq_incomplete.merge(bbq_missing_items)

12. Merging two hashes

Yes! This saves a lot of re-writing and extra work!

Looking keys up

The method .keys allow us to see all the keys in our hash:

13. Getting all the keys in a hash

Finding the length/size of the hash

By using the .length or .size method, we can find out how many key/value pairs are in our hash:

14. Finding the number of key-value pairs in a hash

Okay, so all of this gives us a brief introduction to hashes and things that we can do with them. To find out more hash methods, click here. However, in your coding life, you will find that simple hashes as not very common. I will write more about nested hashes and how to iterate over them in the next blog. For now, let’s go back to our bbq array (finally!) and learn how to make that array into a hash.

Arrays to hashes

You will find that in Ruby and programming in general, there are different ways to achieve the same result. I will show you one way of creating a hash with the same items as those listed in the bbq_meal array. You can Google other methods, and I would suggest sticking to the one that makes the most sense to you.

First, we will create an empty hash for our bbq_items.

15. Creating an empty hash

Then, we will iterate over our array.

Don’t worry! I will explain it in plain English and hopefully, it will help you understand the code.

There are several ways to iterate over an array, the most common ones are each, map, find and select. This topic is very broad so we won’t go into detail, yet.

For now, we will do a brief intro of what the .each method does.

.each method

The .each method “calls the given block once for each element in self [in the array], passing that element as a parameter” — RubyDocs. This will return the array. Let’s give it a try with a bbq_meal_example array.

bbq_meal_example = [“patty”, “patty”, “patty”, “ketchup”, “cheddar cheese”, “cheddar cheese”, “beer”, “beer”, “beer”, “beer”, “beer”, “beer”, “wine”, “wine”, “wine”]

bbq_meal_example.each {|item| puts item}

16. Iterating over an array

Okay, what happened? We iterated over each item in the array (each item inside the |block|) and carried out the operation after the block (“puts item”). So we want to put each item in the array as we iterate over it. Remember that puts and prints are similar, but puts adds a new line after executing. Then, we see that automatically, our initial array is returned.

Let’s try something different:

bbq_meal_example.each {|item| puts “Remember to buy a(n) #{item}!”}

We can also interpolate within our .each method. In this case, we will iterate over each item in the array and for each item, we will put the string “Remember to buy a(n) (and the item in the array)”. Have a look:

17. Example of an .each iteration

It makes more sense now, doesn’t it?

Ok, back to our BBQ!

First, we created a new empty hash called: bbq_meal_hash

Now, we will iterate over the bbq_meal array. What we want to do is create key-value pairs of the items within the bbq_meal_hash. So, whilst iterating over the array, we will add an item as a key of the hash, only if this key does not exist in the hash. If we have an empty hash and we are iterating over a beer, we will add “beer” to the hash as a key. However, if we already have a beer item in our hash, we will only add one value to it. Let’s see how it looks, this should help you understand what I’m saying.

We will not write the .each method in one same line this time, as this will be a long method and we want it to be easy to read.

18. Iterating over an array and moving items into a hash

Now, let’s go over it one more time. In line 1 what we are asking is to iterate over each item of the array. Line 2 says if the bbq_meal_hash has a key which is equal to this item that I am iterating over, then (line 3) please add 1 to its value (value as in the key-value pair). The item is the key and the quantity is the value. In line 4, we are saying, if this is not the case (else), then (line 5) assign a value of 1 to the key which is named after the item we are iterating over.

When we run this code, it will return the array. Remember that .each will always return the array.

We can then call on our hash to see the results.

19. Results

In a text editor, our bbq_meal_hash will now look like this:

20. BBQ_meal_hash!

I hope this has helped you understand the basics of hashes and how to iterate over an array with multiple and duplicate items to make a hash that is easier to read and more organised. Share if you found it helpful!

--

--