Hashes#

Hash is the another collection of objects. It is quite similar to array - it may contain a variety of objects. The difference is the index: in the array the index is a positive integer, in hashes the index could be any object (for the record: any hashable object). We call the index key, so we can say that Hash object is a collection of pairs: key, value.

Hash Syntax#

The primary syntax for a hash is a curly bracket and => sequence to describe key and value: { key => value }. Empty hash is {}.

h = {1=>'one', 3=>'three', 'four'=>4, 2=>'two'}
#=> {1=>"one", 3=>"three", "four"=>4, 2=>"two"}

Accessing Hashes#

To get the object from the hash, use square brackets - the same way as in arrays. To update a value, assign it to the specified key. To add the pair key => value, use a new key.

h = {1=>'one', 3=>'three', 'four'=>4, :two=>'two'}
#=> {1=>"one", 3=>"three", "four"=>4, :two=>"two"}

h[1]           # get object with key integer 1
#=> "one"

h["four"]      # get value of key string "four"
#=> 4

h[:two]="too"  # change the value of key :two
#=> "too"

h[:four]=4.0   # add a new entry: :four =>
#=> 4.0

h              # notice that "four" and :four are not the same keys
#=> {1=>"one", 3=>"three", "four"=>4, :two=>"too", :four=>4.0}

Symbols as Hashes Keys#

Symbol object are very often used as a keys for hashes. To simplify the syntax Ruby introduces a special syntactic sugar: instead writing { :key => value } you can use the colon syntax { key: value }:

h = {one: 1, two: 2, three: 'three'}
#=> {:one=>1, :two=>2, :three=>"three"}

Syntactic sugar in programming is another way to write the same code, designed to be easier to write and remember for humans.

Default Hash Value#

Hash returns nil, if key is not found. You can change this default value by adding a parameter to Hash.new constructor or use default method.

h[:forty_two]
#=> nil          # key not found

h.default = 42   # change the default value
#=> 42

h[:forty_two]    # hash returns default value when key not found
#=> 42

empty = Hash.new('forty two')  # another way to set up the default value
#=> {}

empty[42]                      # hash returns default value when key not found
#=> "forty two"

Accessing Keys and Values#

There are methods to extract keys or values from the hash and to convert it to array of key/value pairs.

h = {one: 1, two: 2, three: 'three'}
#=> {:one=>1, :two=>2, :three=>"three"}

h.keys                 # returns array of keys only
#=> [:one, :two, :three]

h.values               # returns array of values only
#=> [1, 2, "three"]

h.to_a                 # returns array of key/value pairs
#=> [[:one, 1], [:two, 2], [:three, "three"]]

Inverting Hashes#

To invert the hash (change keys to values and vice versa) use invert method. Be warned that it could change the size of the hash, because keys are unique, but values doesn’t have to be.

h = {one: 1, two: 2, three: 2}
#=> {:one=>1, :two=>2, :three=>2}

h.invert
#=> {1=>:one, 2=>:three}  # inverted hash could be smaller than the original

Searching Hashes#

To search for the value in a hash, use key method. This will return the key of the first found value.

h = {one: 1, two: 2, three: 2}
#=> {:one=>1, :two=>2, :three=>2}

h.key(2)
#=> :two

Deleting Object from Hashes#

And to delete the element from the hash, use delete method

h = {one: 1, two: 2, three: 2}
#=> {:one=>1, :two=>2, :three=>2}

h.delete(:three)
#=> 2              # delete returns the value of deleted key

h                  # or nil if not found
#=> {:one=>1, :two=>2}

Merging Two Hashes#

Finally, quite often used function is hash.merge(other_hash), which returns a new hash containing the both hashes. If there are the same keys, the one from other_hash overwrites.

h = {1 => 'one', 2 => 'too'}
#=> {1=>"one", 2=>"too"}

h.merge({2=>'two', 3=>'three'})        # merge h with the other hash
#=> {1=>"one", 2=>"two", 3=>"three"}   # key 2 is overwritten by the key from the other hash