Ruby 2 Hashes

Hashes (sometimes known as associative arrays, maps, or dictionaries) are similar to arrays in that they are indexed collection of object references. However, while you index arrays with integers, you can index a hash with objects of any types: strings, regular expressions, and so on. When you store a value in a hash, you actually supply two objects - the index (normally called the key) and the value. You can subsequently retrieve the value by indexing the hash with the same key. The values in a hash can be objects of any type.
The example p040myhash.rb below, uses hash literals: a list of key => value pairs between braces.
  1. # p040myhash.rb  
  2. h = {'dog' => 'canine''cat' => 'feline''donkey' => 'asinine', 12 => 'dodecine'}  
  3. puts h.length  # 4  
  4. puts h['dog']  # 'canine'  
  5. puts h  
  6. puts h[12]  
The output is:
  1. >ruby p040myhash.rb  
  2. 4  
  3. canine  
  4. {"dog"=>"canine""cat"=>"feline""donkey"=>"asinine", 12=>"dodecine"}  
  5. dodecine  
  6. >Exit code: 0  
Compared with arrays, hashes have one significant advantage: they can use any object as an index.
Hashes have a default value. This value is returned when an attempt is made to access keys that do not exist in the hash. By default this value is nil.
The Hash class has many methods and you can refer them here.

Using Symbols as Hash Keys

Whenever you would otherwise use a quoted string, use a symbol instead. See the following examplep041symbolhash.rb
  1. # p041symbolhash.rb  
  2. people = Hash.new  
  3. people[:nickname] = 'IndianGuru'  
  4. people[:language] = 'Marathi'  
  5. people[:lastname] = 'Talim'  
  6.   
  7. puts people[:lastname# Talim  
Another example is p0411symbolhash.rb
  1. # p0411symbolhash.rb  
  2. h = {:nickname => 'IndianGuru':language => 'Marathi':lastname => 'Talim'}  
  3. puts h  
The output is:
  1. {:nickname=>"IndianGuru":language=>"Marathi":lastname=>"Talim"}  
Another way (using name: value pairs to create a hash if the keys are symbols) of doing the same thing is as shown inp0412symbolhash.rb
  1. # p0412symbolhash.rb  
  2. h = {nickname: 'IndianGuru', language: 'Marathi', lastname: 'Talim'}  
  3. puts h  
The output is:
  1. {:nickname=>"IndianGuru":language=>"Marathi":lastname=>"Talim"}  
Exactly the same as in p0411symbolhash.rb
An exception to the shorter {symbol: value} syntax is when you would like to use a numeric key:
  1. hash = {1: 'one'# will not work  
  2. hash = {1 => 'one'# will work