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

Get Mastering Chef now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.