Ruby Hashes Tutorial

In this section, we will learn what the Hashes are and how to use them in Ruby.

What is Hashes in Ruby?

Ruby Hash is a collection-type object like Arrays where you can store multiple values in a Hash object.

Hashes use keys to store elements in their bodies.

Note: keys are the way of setting and accessing values in hashes. For example, keys in Arrays are the index numbers that we used to access the values stored in an array. They are implicitly set and there’s no way for us to use other types of keys that are easier to remember (for example, string-type keys).

But with Hashes, we are responsible to explicitly set the keys as well!

The major benefit of explicitly setting the keys is that we can choose other types of keys as well! For example, the key could be of type string! This way we can set a key that is easier to remember when in later time we wanted to access a specific value in a Hash.

For example, let’s say you have a list of phone numbers and want to store it in a collection-type object like an array or hash.

If you pick array, then you’ll have the trouble finding a specific phone number in the list! Basically, you need to check each element in the array to see if it matches the target phone number you want.

But if you use a Hash object, you can attach a key to each phone number (for example use the name of the owner of each phone number as the key) and then in later time just use the name of the person to get its phone number from the Hash object!

Alright, let’s get into the details of Hashes and see how we can create and use one in a Ruby program.

How to Create Hashes in Ruby? (Ruby Hashes Syntax)

There are two ways of creating a Hash object in Ruby.

The first one is using Hash literal, which is used for when we know the keys and values that we want to store into a hash object in advance!

This is the syntax of Hash literals:

{key => value, key2=> value2, key_n => value_n}

`{}`: in order to create a hash literal we start with a pair of braces and within the body of this pair we put the keys and values.

`keys`: As mentioned before, each value in hash should have a relative “thing” that could be used in the future to access that value! That “thing” is called key! The key can be of types other than just numbers! For example, you can use string-type key or Symbol-type key etc.

`value`: this is the value we want to store in a hash object with its relative key. Note that any type of object can be stored in a hash object! Basically, you can put another hash object, an array, a string value, a custom made object etc. as a value in a Hash object.

`=>`: sometimes people call this symbol as rocket symbol (because of its shape that looks like a rocket) and we use it to separate a key from its relative value.

`,`: Now if in a hash you’re putting more than one key-value, you need to separate them using a comma.

Note: the important note to remember is that `keys` are unique in a hash object! This means you can’t have two keys in a hash object with the same identity! If you put the same key in a hash object that is already there, it will update the old key with a new value instead of adding both to the same object!

The second way of creating a Hash object in Ruby is by using the Hash class and creating an object from there.

Here’s the syntax of using the Hash class:

hashObj = Hash.new

The syntax above will give an empty hash object which then you’re responsible for adding new key-values.

or

hashObj = Hash.new (“defualtValue”)

Note: in the next section, we will talk about Hash objects with default values (what they are and how they work).

Example: creating Hashes in Ruby

hasObj = {
    :name =>"John", 
    :lastName => "Doe",
    :age => 100
}

As you can see, the `hashObj` in this example has three keys (which are of type Symbol) and they each have its own value as well. (Also, we separated them using comma)

How to Access Hashes Elements in Ruby?

The way we access a hash value in Ruby is exactly the same as the way we access a value in an Array.

Basically, we use a pair of bracket after the name of the target hash object and put the target key within this pair to get the value from the target hash object!

Here’s the syntax:

hasObject[key]

`hashObject`: this is the hash object we want to search for a key in it and get its value if the key is there.

`[key]`: here we put the key we want to take its value from the hash.

Note: if the target key was not in the object, we will get a nil value as a result.

Example: accessing Hashes elements in Ruby

hasObj = {
    :name =>"John", 
    :lastName => "Doe",
    :age => 100
}

puts hasObj[:name]
puts hasObj[:lastName]
puts hasObj[:age]

Output:

John

Doe

100

Ruby Hashes: Adding new key-value to a Hash object

If you call a key on top of a hash object and on the left side of the assignment operator in order to add a value to it, two things can happen:

  • If the key was not in the target hash object, then it will be added to the hash with its value (the one we set on the right side of the assignment operator).
  • If the key is already in the target hash, then the value will replace the old one that is already set for the specified key.

Example: adding new key-value pair to a hash object

person = {
    :name =>"John", 
    :lastName => "Doe",
    :age => 100,
    "id"=> 542242, 
    "company"=>"Google"
}


person[:name] = "Jack"
person[:city] = "LA"
person[:salary] = 100000000

puts person.to_s

Output:

{:name=>"Jack", :lastName=>"Doe", :age=>100, "id"=>542242, "company"=>"Google", :city=>"LA", :salary=>100000000}

Length of Hashes in Ruby

The length of a Hash object is equal to the number of entries it currently has (each pair of key-value in a hash object is called an entry).

Also, we use the `length` method in order to get the length of a hash object.

Example: getting the length of hashes in Ruby

person = {
    :name =>"John", 
    :lastName => "Doe",
    :age => 100,
    "id"=> 542242, 
    "company"=>"Google"
}

puts "The length of the hash object is: #{person.length}"

Output:

The length of the hash object is: 5

Ruby Hashes: getting keys

If for any reason you wanted to get a list of all the keys currently available in a hash object, you can call the `keys` method on top of the target hash object, which will return an array that contains all the keys.

Example: getting the keys from Ruby Hashes

person = {
    :name =>"John", 
    :lastName => "Doe",
    :age => 100,
    "id"=> 542242, 
    "company"=>"Google"
}

for key in person.keys do 
    puts "The key is: #{key}"
end 

Output:

The key is: name

The key is: lastName

The key is: age

The key is: id

The key is: company

Ruby Hashes: getting values

The same can happen for values as well! Basically, we can call the `values` method on top of a hash object and get the entire values already in the target hash object.

(The return value of this method is of type array)

Example: getting values from Ruby Hashes

person = {
    :name =>"John", 
    :lastName => "Doe",
    :age => 100,
    "id"=> 542242, 
    "company"=>"Google"
}

for value in person.values do 
    puts "The value is: #{value}"
end 

Output:

The value is: John

The value is: Doe

The value is: 100

The value is: 542242

The value is: Google

Ruby Hashes: Checking for Keys

Ruby hash object has a method called has_key? by which we can check a hash object to see if it has a specific key in it or not.

If the hash object had the specified key (which we set as the argument of the method) the return value will be then true, otherwise the value false will return instead.

Example: checking for a key in Ruby hashes using the has_key? method

person = {
    :name =>"John", 
    :lastName => "Doe",
    :age => 100,
    "id"=> 542242, 
    "company"=>"Google"
}

if person.has_key?(:name)
    puts "Yes, the hash object has the :name key in it"
else 
    puts "No, this hash object does not have the specified key"
end 

Output:

Yes, the hash object has the :name key in it

Ruby Hashes: Checking for Values

Just like the `has_key?` method that we use to check for a key, there’s another method called has_value? which can be used to check a Hash object and see if it has the specified value in the target hash object or not.

If the target hash object had the specified value (which we set as the argument of the method) then the return value will be true, otherwise the value false will return instead.

Example: checking for a value in Ruby hashes using the has_value? method

person = {
    :name =>"John", 
    :lastName => "Doe",
    :age => 100,
    "id"=> 542242, 
    "company"=>"Google"
}

if person.has_value?("Doe")
    puts "Yes, the hash object has the Doe value in it"
else 
    puts "No, this hash object does not have the specified value"
end 

Output:

Yes, the hash object has the Doe value in it

Ruby Hashes as Method Parameters

We can pass a hash object as the argument to the parameter of a method as well!

In that case, only a reference of that hash object will be passed to the method! This means if we changed the value of a key within the body of the target method, this change will affect the main hash object.

Example: using Hashes as the argument to methods

person = {
    :name =>"John", 
    :lastName => "Doe",
    :age => 100,
    "id"=> 542242, 
    "company"=>"Google"
}


def modify (param)
    param[:name] = "Jack"
    param[:lastName] = "Bauer"
end 

modify(person)

puts person[:name], person[:lastName]

Output:

Jack

Bauer

Ruby Hashes: Removing Elements

Hash objects in Ruby have also a method called delete by which we can remove a key-value pair from the target hash object.

This method simply takes the target key (that we want to remove) as its argument and searches the Hash object for this key. If it found one, it will remove that and return its value (the value of the removed key) as its return value.

If the specified key that we set as the argument of the method was not in the target hash object, the return value of this method will be nil then.

Example: removing elements from Ruby hashes

person = {
    :name =>"John", 
    :lastName => "Doe",
    :age => 100,
    "id"=> 542242, 
    "company"=>"Google"
}

puts "The content of the hash before calling the delete method: #{person.to_s}"

person.delete(:name)
person.delete(:lastName)

puts "The contentn of the hash after calling the delete method: #{person.to_s}"

Output:

The content of the hash before calling the delete method: {:name=>"John", :lastName=>"Doe", :age=>100, "id"=>542242, "company"=>"Google"}

The contentn of the hash after calling the delete method: {:age=>100, “id”=>542242, “company”=>”Google”}

More to Read:

Ruby Hashes and Default Value

Ruby Hashes and Block

 

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies