Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book


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 up a key that doesn't exist, you get nil back.


To take control of this behavior, specify a default value when creating the hash. If you change the first line of the example to h = Hash.new("hospitable"), h["Missouri"] returns "hospitable". Then again, so does h["Antarctica"].

Hashes are often used for expressing categorizations. Suppose a business is closed on Sundays, and its employees each have Sunday off plus one other day of the week. Then to keep a record of who is off when is to establish six categories of employees, one for each weekday plus Saturday. One possible way of representing that information is with a hash, using employee names as keys.

 day_off = {
 "Julia" => "Monday",
 "Martha" => "Saturday",
 "Thomas" => "Thursday",
 "Alex" => "Friday",
 "Shamsul" => "Wednesday",
 "Holly" => "Saturday",
 "Jack" => "Tuesday",
 "Carol" => "Thursday"

Alternatively, we can organize the same information in six arrays.

 monday_off = ["Julia"]
 tuesday_off = ["Jack"]
 wednesday_off = ["Shamsul"]
 thursday_off = ["Thomas", "Carol"]
 friday_off = ["Alex"]
 saturday_off = ["Martha", "Holly"]

It might seem that using arrays would be a more efficient and intuitive way, particularly if there were a very large number of employees. But consider how hard it would be later when you needed to look up Martha's day off. You'd have to pick up each array and scan it, then produce a value that would depend on which array you were looking at when you found her name. That's both inefficient and confusing. Having a hash means you can look up the answer using day_off["Martha"] and be done with it. Hashes can take up more room than arrays, depending on how you use them, but they can also help you do some things more quickly and easily.

A few Useful Hash Instance Methods

keys, values

Return either the keys or values as an array.

 taste = {"cake"=>"sweet", "lemon"=>"sour",
 "fries"=>"greasy", "pepper"=>"hot"}
 taste.keys #-> ["fries", "cake", "pepper", "lemon"]
 taste.values #-> ["greasy", "sweet", "hot", "sour"]

key?(x), value?(x)

Test whether x exists as a key or a value.

 taste.key?("pepper") #–> true
 taste.key?("sour") #–> false
 taste.value?("sour") #–> true


Get a copy in array form, where each element is a key, value array.

 { 1=>1, 3=>27, 5=>125 }.to_a
 #-> [[5, 125], [1, 1], [3, 27]]

Notice that the hash produces its key, value pairs in a seemingly arbitrary order. Information in arrays is ordered by numbered slots, but hashes cannot be considered ordered containers.

  • + Share This
  • 🔖 Save To Your Account