9.3. Hashes

Like an array, a hash is a collection of objects. A hash consists of key/value pairs, where any key and any value can be any Ruby object. Hashes let you perform lookup operations based on keys. In addition to simple key-based value retrieval, you can also perform more complex filtering and selection operations.

A typical use of a hash is to store complete strings along with their abbreviations. Here’s a hash containing a selection of names and two-letter state abbreviations, along with some code that exercises it. The => operator connects a key on the left with the value corresponding to it on the right:

state_hash = { "Connecticut" => "CT", "Delaware" => "DE", "New Jersey" => "NJ", "Virginia" => "VA" } print "Enter the name of a ...

Get The Well-Grounded Rubyist, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.