Ruby Hashes


A Hash is a collection of key-value pairs like this: "employee" => "salary". It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index.

The order in which you traverse a hash by either key or value may seem arbitrary, and will generally not be in the insertion order. If you attempt to access a hash with a key that does not exist, the method will return nil

Notice: This does change, Hashes are ordered since Ruby 1.9.

Creating Hashes:

Notice that you create hashes using {squigly brackets} instead of the [square brackets] used for arrays:

      friends = {
      	"first name" => "Ronald",
      	"last name"  => "McNamara",
      	"address"    => "36 Long Road",  
      	"city"       => "Tamika",
      	"province"   => "Tazmania"
      }
      

As with arrays, there is a variety of ways to create hashes. You can create an empty hash with the new class method:

      months = Hash.new
      puts months.inspect
      

This will produce following result:

      {}
      

You can also use new to create a hash with a default value, which is otherwise just nil:

      months = Hash.new( "month" )
      puts months.inspect
      weeks = Hash.new "week"
      puts weeks.inspect
      

This will produce following result:

      {}
      {}
      

When you access any key in a hash that has a default value, if the key or value doesn't exist, accessing the hash will return the default value:

      months = Hash.new( "month" )
      
      puts months[0].inspect
      puts months[72].inspect
      

This will produce following result:

      "month"
      "month"
      

Here is a simple way of creating and accessing Hash keys/values:

      H = Hash["a" => 100, "b" => 200]
      
      puts H.inspect
      puts H['a'].inspect
      puts H['b'].inspect
      

This will produce following result:

      {"a"=>100, "b"=>200}
      100
      200
      

You can use any Ruby object as a key or value, even an array, so following example is a valid one:

      puts ({[1,"jan"] => "January"}).inspect
      

This will produce following result:

      {[1, "jan"]=>"January"}
      

Hash Built-in Methods:

We need to have an instance of Hash object to call a Hash method. As we have seen, following is the way to create an instance of Hash object:

      h1 = Hash[ 'key' => 'value' ]
      h2 = Hash.new
      h3 = Hash.new { |hash, key| hash[key] = value }
      
      puts h1.inspect
      puts h2.inspect
      puts h3.inspect
      

This will produce following result:

      {"key"=>"value"}
      {}
      {}
      

This will returns a new hash populated with the given objects. Now using created object we can call any available instance methods. For example:

      months = Hash.new( "month" )
      puts months.inspect
      
      months = {"1" => "January", "2" => "February"}
      puts months.inspect
      
      keys = months.keys
      puts keys.inspect
      
      values = months.values
      puts values.inspect
      

This will produce following result:

      {}
      {"1"=>"January", "2"=>"February"}
      ["1", "2"]
      ["January", "February"]
      

If You need to merge two hashes, the merge method will help.

It returns a new hash containing the contents of other_hash and the contents of hsh, overwriting entries in hsh with duplicate keys with those from other_hash.

      h1 = {"d1" => "2009-7-27", "d2" => "2010-3-6"}
      puts h1.inspect
      h2 = {"d1" => "12:29:15", "d2" => "10:00:17"} 
      puts h2.inspect
      
      h = h1.merge(h2){|key, first, second| first + " " + second}
      puts h.inspect
      

This will produce following result:

      {"d1"=>"2009-7-27", "d2"=>"2010-3-6"}
      {"d1"=>"12:29:15", "d2"=>"10:00:17"}
      {"d1"=>"2009-7-27 12:29:15", "d2"=>"2010-3-6 10:00:17"}