Creating and merging Ruby hashes


Jul 02, 2022 | Ruby

Let's start first with what is a hash.

A hash is a data structure used to store some data. This data has a form of key-value pairs. The important thing to remember here is that hashes don't have indexes, so you can't access them like you would with arrays. You will use the keys instead.

Let's create some hashes.

The easiest way to create a hash is like this:

person = {}

We assigned an empty has to a variable called person.

Let's add some data using key-value pairs:

person = {
  name: "Marko",
  last_name: "Manojlovic",
  age: 35
}

In our person hash, name is a key and Marko is the value for that key.

To access our name value, we will use the key to do so, like this:

person[:name]

There is a cool trick you can use to get value in case if a key doesn't exist (non-existing key will return nil):

person.fetch(:phone_number, '')

The fetch method allows you to use the second argument as a default value of what it should return in case there is no key you're trying to access. If you you fetch but don't specify the default value, Ruby will raise an exception.

We can also add new values to our existing hash by defining our key and assigning a value to it like this:

person[:email] = "marko.manojlovic.bg@gmail.com"

So now our person hash looks like this:

{
  name: "Marko",
  last_name: "Manojlovic",
  age: 35,
  email: "marko.manojlovic.bg@gmail.com"
}

When it comes to what value of a hash can be, you can have a Ruby object as a value, or strings, arrays, integers, booleans, floats, etc.
Important: remember that keys are unique, and if you try to add the same key more than once, you will end up changing its value.

We can do other cool things with hashes. For example, we can merge them.

Let's define another hash:

address = {
  street: "123 Awesome Street",
  province: "BC"
}

Merging address hash with our person hash is very simple:

person.merge!(address)
# {:first_name=>"Marko", :last_name=>"Manojlovic", :age=>35, :street=>"123 Awesome Street", :province=>"BC"}

When we are merging hashes, again, we have to remember that keys are unique and that newer values will overwrite older values. So if I had the same key in my address hash, for example name: "Johny", my first_name value will be replaced with the new value -> "Johny".