4.0 Introduction to Ruby Hashes

Creating a Hash

A Hash is a collection of key-value pairs. You retrieve or create a new entry in a Hash by referring to its key. Hashes are also called 'associative arrays', 'dictionary', 'HashMap' etc. in other languages

A blank hash can be declared using two curly braces {}. Here is an example of a Hash in Ruby:

student_ages = {
    "Jack" => 10,
    "Jill" => 12,
    "Bob" => 14
  }

The names (Jack, Jill, Bob) are the 'keys', and 10, 12 and 14 are the corresponding values. Now try creating a simple hash with the following keys and values:

Ramen = 3
Dal Makhani = 4
Tea = 2

Output Window

Fetch values from a Hash

You can retrieve values from a Hash object using [] operator. The key of the required value should be enclosed within these square brackets.

Now try finding the price of a Ramen from the restaurant_menu hash: write the name of the object, follow it with a square bracket, and place the key inside the brackets. In this case the key is a string so enclose the key in quotes.

That was very simple, wasn't it? One small step at a time!

Modifying a Hash

Once you've created a Hash object, you would want to add new key-value pairs as well as modify existing values.

Here is how you would set the price of a "Ramen" in the restaurant_menu hash:

restaurant_menu["Ramen"] = 3

In fact, you can create a blank hash and add all the values later. Now why don't you try assigning the following values to an empty hash?

Dal Makhani: 4.5
Tea: 2

Output Window

Congratulations, guest!


% of the book completed

or

This lesson is Copyright © 2011-2014 by Sidu Ponnappa and Jasim A Basheer