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

Common Hash Methods

Many of the methods used with hashes are the same as those used with arrays. These include each (discussed in Chapter 5), delete, length, index, shift, and sort. Start with this hash:

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

The delete method is provided the key of element to be deleted:


It returns the value deleted in the process.

To find the key associated with a particular value, use index:

abbr = states.index('Maryland') # "MD"

The shift method cuts the first key-value pair from a hash, returning both as an array:

md = states.shift # ["MD", "Maryland"]

The length (and synonymous size) methods return the number of elements in the hash:

count = states.length

The sort method differs from the array’s sort method in that it sorts the elements in the hash by key (hashes can be sorted by value, but doing so requires special syntax not yet covered).

Because hashes have a key-value relationship, there are other methods particular to hashes, not present in arrays. The keys method returns an array of the keys in the hash; values returns an array of the values.

To see if a value is in a hash, use has_value? or the synonym value?:

puts states.has_value?('Quebec') # false

Similarly, has_key?—like its synonyms key?, include?, and member?—returns a Boolean value indicating if the hash has a given key:

puts states.has_key?('MD') # true

Finally, the invert method swaps all the keys and values. The relationship between the two will be maintained, but their roles will be switched (Figure 4.23).

Figure 4.23

Figure 4.23 A demonstration of how the invert function works. Note that it returns the inverted hash without affecting the original.

To use hash methods:

  1. Create a new hash:

    stooges = {'Moe' => 190, 'Larry' =>
    → 190, 'Curly' => 145}

    This hash stores the names of the Three Stooges characters (some of them, anyway), along with the number of shorts in which they appeared (approximately).

  2. Sort the hash by key in alphabetical order (Figure 4.24):

    puts stooges.sort
    Figure 4.24

    Figure 4.24 The creation and sorting of a hash, which is then printed.

    As you can see in Figure 4.24, when puts is called on an entire hash, both the keys and the values will be printed.

  3. Replace Curly with Shemp:

    stooges['Shemp'] = 32

    To remove a hash element, call delete, providing it with the key of the element to be deleted. To add a new element, use the hash name, followed by the new key within square brackets, assigning that a value.

  4. Print out the current contents of the hash (Figure 4.25):

    puts stooges.inspect
    Figure 4.25

    Figure 4.25 One Stooge left, another was added, and the whole hash was printed using inspect.

  • + Share This
  • 🔖 Save To Your Account