Understanding Hashes in Ruby

Few days ago, a friend of mine(named Kwabena) asked me to explain what is meant by a Hash. After explaining it to him, he got familiar with it so i’ve decided to write about what a Hash is today.

What is a Hash ?

First of all, a Hash sometimes called a dictionaries(in Swift), maps(in Golang) or associative arrays(in PHP) is a collection where each value is accessed using a key. A key is an easy way to get a value or data out of your Hash. Hashes are implemented using a Hash Table Algorithm. Hashes are faster and more efficient than Arrays in searching through a large pile of data. For instance; in a typical library, imagine that all the books were arranged in single pile that for you to pick up a certain book, you have to search through every book until the book is found (This is the way an Array works). But for Hashes, the books has been arranged in sections that if you’re looking for a particular Tech related book, you could just go straight to the tech section and search for your book (Cool isn’t it ?).

Moving on, let me show you how to create a Hash in Ruby.

Using a Hash

From the above, we can see how a hash can be used. In Line 3, we created a Hash called student which has a name, age, favorite quote, hobby, and programming language key. We can easily find the values using the key. In Line 9, we print out the value of programming_language using its key.

Like an array, we can also iterate and print all the keys and values of a Hash using an each loop.

Iterating through a Hash

Finally, with this I hope i’ve been able to impact knowledge of hashes to someone somewhere.

remark = “ Thanks for reading :) “

puts remark

output: Thanks for reading

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.