Hashes Implementation in Ruby
Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. The major difference between arrays in hashes is in the custom set up of hash indexes. Indexes in arrays are numeric and indexes in hashes can be of any object type you decide to use.
Ruby specifies two ways of creating hashes.
- my_hash = {:one=>1, :two=>2} or alternatively my_hash = {one=>1, two=>2}
- my_hash = Hash[:one,1, :two:2]
Accessing hashes follows similar to array access pattern of passing an index to a hash in square brackets.
my_hash[:one] //returns 1
my_hash[:three] = 3 //adds new hash element to 3 with index of three
Hashes can be interrogated for other types of information such as list of indexes, values or conversion of hash into an array.
my_hash.key
my_hash.values
my_hash.to_a
It is important to note that hashes contain references to object and not objects themselves. Hashes are used in storing key-value pairs and array can always be used in case key-value par is not required. Both, arrays and hashes can be traversed for the information at about the same efficiency rate. Once again, the main difference between hashes and arrays are in the type of key: either number or objects.
It is interesting to note that hashes in Ruby are actually implemented as arrays.