June 2015
Intermediate to advanced
374 pages
7h 19m
English
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.
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
Read now
Unlock full access