Publishers of technology books, eBooks, and videos for creative people

Home > Articles

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

This chapter is from the book

Creating a Hash

A hash is like an array in many ways, except a hash uses associated keys (in some languages these are called associative arrays). Whereas arrays use numeric indexes, from 0 to array.length - 1, hashes use meaningful indexes, normally strings or symbols.

To create a hash, use this syntax:

my_hash = {'key' => 'value'}

To create a hash with multiple elements, separate each key-value pair with a comma:

states = {'MD' => 'Maryland', 'IA' =>
→ 'Iowa'}

To refer to a hash element, use its key, just as you would an index position in an array:

puts states['MD']

Referring to a hash key that doesn’t exist returns the value nil:

puts states['QC'] # nil

To add items to a hash, you can simply do this:

states['IL'] = 'Illinois'

In situations where the keys are representative of values and don’t need to be used as strings themselves, symbols make a logical choice:

me = {:name => 'Larry', :age => 87}

To practice using hashes, this next sequence of steps will build up a multidimensional hash: a hash where its element values are also hashes.

To use hashes:

  1. Create two hashes:

    english = {:name => 'Grammar',
    → :teacher => 'Ms. Krabapple'}
    science = {:name => 'Physics',
    → :teacher => 'Mr. Frink'}

    Both hashes contain two elements, one indexed at :name and the other at :teacher.

  2. Create a multidimensional hash (Figure 4.21):

    classes = {'english' => english,
    → 'science' => science}
    Figure 4.21

    Figure 4.21 The multidimensional classes hash contains two elements, each of which is a hash that also has two elements.

    To create a multidimensional hash, a new variable is created using the key-value syntax. In this case, however, the values are other hashes. You don’t need to create the english and science hash variables as I do in Step 1, but for the sake of learning, it keeps the syntax cleaner and easier to follow.

  3. Print the name of the person that teaches the English course:

    puts classes['english'][:teacher]

    When working with multidimensional hashes, refer to the first dimension’s key within square brackets, followed by the second dimension’s key with square brackets. In this case, the first dimension uses strings for keys while the second uses symbols.

  4. Print the name of the science course (Figure 4.22):

    puts classes['science'][:name]
    Figure 4.22

    Figure 4.22 The values of two specific hash elements are printed.

  • + Share This
  • 🔖 Save To Your Account