Hashes
Hashes are also known as associative arrays, and they are dictionary-like objects, comprising keys and their associated values. Hashes are very similar to arrays; however, while arrays allow only integers to be used as an index, hashes, on the other hand, can use any object as a key.
Creating hashes
Hashes can be created easily using their implicit form as follows:
scores = { "A" => 85, "B" => 70, "C" => 60, "D" => 50, "E" => 35 }
Here, A
, B
, C
, D
, and E
are keys having associated values 85
, 70
, 60
, 50
, and 35
, respectively.
Hashes also allow for a form wherein keys are always symbols:
scores = { :A => 85, :B => 70, :C => 60, :D => 50, :E => 35 }
We may access each key's value using the corresponding symbol as follows:
scores[:A] #=> 85
We can also create a new hash using the new
method of the Hash
class:
scores = Hash.new scores["A"] = 85
If no default value is set while creating a hash, then, when we try to access the key, it'll return nil. One can...