Hashes

Array elements are referred to by numeric indices. A more general approach would be to allow any kind of object, not just a number, to refer to an array element. A hash, sometimes also called a dictionary or an associative array, has this ability.

h = Hash.new
h["Alabama"] = "humid"
h["Alaska"]  = "frigid"
h["Colorado"]  = "rocky"
h["Wisconsin"] = "cheesy"

# If you prefer, the above can also be written this way:
# h = {"Alabama"=>"humid",  "Alaska"=>"frigid",
#  "Colorado"=>"rocky", "Wisconsin"=>"cheesy"}

h.size  #–> 4
h["Alaska"]    #–> "frigid"
h["Missouri"]  #–> nil

What a hash gives you is essentially a two-column table with keys in one column and values in the other. Give the hash a key, and it tells you the associated value. If you look ...

Get Sams Teach Yourself Ruby in 21 Days 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.