Hash in Ruby

Learn how to use a hash in Ruby language.

We'll cover the following

Defining hash in Ruby

To define a hash in a Ruby program, we need to use curly brackets. Remember that we use square brackets for arrays:

$ pry
> obj = {}
...
> obj.class
Hash < Object

We should not name the variable hash because it is a reserved language keyword, but we can enter it into the REPL and see what happens. That’s why the authors usually use obj (object) orhh(double “h” indicates it’s more than just a variable).

Programmers say that the hash is key-value storage, where each key is assigned a value. For example, the key is ball, a string, and the value is the physical object ball itself. The hash is often called a dictionary. This is partly true because the dictionary of words is a perfect example of hash. Each key, or word, has a meaning, or a description of the word or a translation. In Java, language hash used to be called a dictionary too, but since the seventh version, this concept has become obsolete, and the dictionary has been renamed to map.

The key and value in the hash can be any object, but most often, the key is a string or symbol, and the value is the actual object. It is difficult to predict what it will be. It can be a string, a symbol, an array, a number, another hash. So when developers define a hash in a Ruby program, they usually know in advance what type it will keep.

For example, let’s agree that the key in the hash is a symbol, and the value is a number, type integer. We’ll keep the weight of different types of balls in grams inside of our hash:

obj = {}
obj[:soccer_ball] = 410
obj[:tennis_ball] = 58
obj[:golf_ball] = 45 

If we write this program into the REPL and type obj, we will see the following:

{
    :soccer_ball => 410,
    :tennis_ball => 58,
      :golf_ball => 45
}

The text above is perfectly valid from Ruby’s language perspective, and we could initialize our hash without writing the values and without using assignment operator =:

obj = {
    :soccer_ball => 410,
    :tennis_ball => 58,
      :golf_ball => 45
}

The operator => in Ruby is called a hash rocket. In JavaScript, it’s known as “fat arrow,” but has a different meaning. However, the hash rocket notation is now obsolete. It would be more correct to write the program this way:

obj = {
  soccer_ball: 410,
  tennis_ball: 58,
  golf_ball: 45
}

We should notice that even though the record looks different, we will get the same conclusion as above if we write obj in REPL. In other words, the keys, :soccer_ball, :tennis_ball, :golf_ball, are symbol types in this case.

To get the value back from the hash, use the following construction:

puts 'Golf ball weight:'
puts obj[:golf_ball]

Get hands-on with 1200+ tech skills courses.