Home > Articles > Programming > Ruby

This chapter is from the book

This chapter is from the book

Working with Hashes

Hashes are known in some circles as associative arrays, dictionaries, and by various other names. Perl and Java programmers in particular will be familiar with this data structure.

Think of an array as an entity that creates an association between index x and data item y. A hash creates a similar association, with at least two exceptions. First, for an array, x is always an integer; for a hash, it need not be. Second, an array is an ordered data structure; a hash typically has no ordering.

A hash key can be of any arbitrary type. As a side effect, this makes a hash a nonsequential data structure. In an array, we know that element 4 follows element 3; but in a hash, the key may be of a type that does not define a real predecessor or successor. For this reason (and others), there is no notion in Ruby of the pairs in a hash being in any particular order.

You may think of a hash as an array with a specialized index, or as a database "synonym table" with two fields, stored in memory. Regardless of how you perceive it, it is a powerful and useful programming construct.

Creating a New Hash

As with Array, the special class method [] is used to create a hash. The data items listed in the brackets are used to form the mapping of the hash.

Six ways of calling this method are shown here (note that hashes a1 through c2 will all be populated identically):

  a1 = Hash.[]("flat",3,"curved",2)
  a2 = Hash.[]("flat"=>3,"curved"=>2)
  b1 = Hash["flat",3,"curved",2]
  b2 = Hash["flat"=>3,"curved"=>2]
  c1 = {"flat",3,"curved",2}
  c2 = {"flat"=>3,"curved"=>2}
  # For a1, b1, and c1: There must be
  # an even number of elements.

Also, the class method new can take a parameter specifying a default value. Note that this default value is not actually part of the hash; it is simply a value returned in place of nil. Here's an example:

  d = Hash.new     # Create an empty hash
  e = Hash.new(99)   # Create an empty hash
  f = Hash.new("a"=>3) # Create an empty hash
  e["angled"]     # 99
  e.inspect      # {}
  f["b"]        # {"a"=>3} (default value is
             #  actually a hash itself)
  f.inspect      # {}

Specifying a Default Value for a Hash

The default value of a hash is an object that is referenced in place of nil in the case of a missing key. This is useful if you plan to use methods with the hash value that are not defined for nil. It can be assigned upon creation of the hash or at a later time using the default= method.

All missing keys point to the same default value object, so changing the default value has a side effect:

  a = Hash.new("missing") # default value object is "missing"
  a["hello"]        # "missing"
  a.default="nothing"
  a["hello"]        # "nothing"
  a["good"] << "bye"    # "nothingbye"
  a.default        # "nothingbye"

The special instance method fetch raises an IndexError exception if the key does not exist in the Hash object. It takes a second parameter that serves as a default value. Also, fetch optionally accepts a block to produce a default value in case the key is not found. This is in contrast to default, because the block allows each missing key to have its own default. Here's an example:

  a = {"flat",3,"curved",2,"angled",5}
  a.fetch("pointed")          # IndexError
  a.fetch("curved","na")        # 2
  a.fetch("x","na")          # "na"
  a.fetch("flat") {|x| x.upcase}    # 3
  a.fetch("pointed") {|x| x.upcase}  # "POINTED"

Accessing and Adding Key/Value Pairs

Hash has class methods [] and []=, just as Array has; they are used much the same way, except that they accept only one parameter. The parameter can be any object, not just a string (although string objects are commonly used). Here's an example:

  a = {}
  a["flat"] = 3    # {"flat"=>3}
  a.[]=("curved",2)  # {"flat"=>3,"curved"=>2}
  a.store("angled",5) # {"flat"=>3,"curved"=>2,"angled"=>5}

The method store is simply an alias for the []= method, both of which take two arguments, as shown in the example.

The method fetch is similar to the [] method, except that it raises an IndexError for missing keys. It also has an optional second argument (or alternatively a code block) for dealing with default values (see the section "Specifying a Default Value for a Hash"). Here's an example:

  a["flat"]    # 3
  a.[]("flat")   # 3
  a.fetch("flat") # 3
  a["bent"]    # nil

Suppose you are not sure whether the Hash object exists, and you would like to avoid clearing an existing hash. The obvious way is to check whether the hash is defined, as shown here:

  unless defined? a
   a={}
  end
  a["flat"] = 3

Another way to do this is as follows:

  a ||= {}
  a["flat"] = 3

The same problem can be applied to individual keys, where you only want to assign a value if the key does not exist:

  a=Hash.new(99)
  a[2]       # 99
  a        # {}
  a[2] ||= 5    # 99
  a        # {}
  b=Hash.new
  b        # {}
  b[2]       # nil
  b[2] ||= 5    # 5
  b        # {2=>5}

Note that nil may be used as either a key or an associated value:

  b={}
  b[2]   # nil
  b[3]=nil
  b     # {3=>nil}
  b[2].nil? # true
  b[3].nil? # true
  b[nil]=5
  b     # {3=>nil,nil=>5}
  b[nil]  # 5
  b[b[3]]  # 5

Deleting Key/Value Pairs

Key/value pairs of a Hash object can be deleted using clear, delete, delete_if, reject, reject!, and shift.

Use clear to remove all key/value pairs. This is essentially the same as assigning a new empty hash, but it's marginally faster.

Use shift to remove an unspecified key/value pair. This method returns the pair as a two-element array (or nil if no keys are left):

  a = {1=>2, 3=>4}
  b = a.shift    # [1,2]
  # a is now {3=>4}

Use delete to remove a specific key/value pair. It accepts a key and returns the value associated with the key removed (if found). If the key is not found, the default value is returned. It also accepts a block to produce a unique default value rather than just a reused object reference. Here's an example:

  a = {1=>1, 2=>4, 3=>9, 4=>16}
  a.delete(3)           # 9
  # a is now {1=>1, 2=>4, 4=>16}
  a.delete(5)           # nil in this case
  a.delete(6) { "not found" }   # "not found"

Use delete_if, reject, or reject! in conjunction with the required block to delete all keys for which the block evaluates to true. The method reject uses a copy of the hash, and reject! returns nil if no changes were made.

Iterating over a Hash

The Hash class has the standard iterator each, as is to be expected. It also has each_key, each_pair, and each_value (each_pair is an alias for each). Here's an example:

  {"a"=>3,"b"=>2}.each do |key, val|
   print val, " from ", key, "; "  # 3 from a; 2 from b;
  end

The other two provide only one or the other (the key or the value) to the block:

  {"a"=>3,"b"=>2}.each_key do |key|
   print "key = #{key};"   # Prints: key = a; key = b;
  end

  {"a"=>3,"b"=>2}.each_value do |value|
   print "val = #{value};"  # Prints: val = 3; val = 2;
  end

Inverting a Hash

Inverting a hash in Ruby is trivial with the invert method:

  a = {"fred"=>"555-1122","jane"=>"555-7779"}
  b = a.invert
  b["555-7779"]   # "jane"

Because hashes have unique keys, there is potential for data loss when doing this—duplicate associated values will be converted to a unique key using only one of the associated keys as its value. There is no predictable way to tell which one will be used.

Detecting Keys and Values in a Hash

Determining whether a key has been assigned can be done with has_key? or any one of its aliases: include?, key?, or member?. Here's an example:

  a = {"a"=>1,"b"=>2}
  a.has_key? "c"    # false
  a.include? "a"    # true
  a.key? 2       # false
  a.member? "b"     # true

You can also use empty? to see whether there are any keys at all left in the hash; length or its alias size can be used to determine how many there are, as shown here:

  a.empty?    # false
  a.length    # 2

Alternatively, you can test for the existence of an associated value using has_value? or value?:

  a.has_value? 2    # true
  a.value? 99      # false

Extracting Hashes into Arrays

To convert the entire hash into an array, use the to_a method. In the resulting array, keys will be even-numbered elements (starting with 0) and values will be odd-numbered elements of the array:

  h = {"a"=>1,"b"=>2}
  h.to_a    # ["a",1,"b",2]

It is also possible to convert only the keys or only the values of the hash into an array:

  h.keys     # ["a","b"]
  h.values    # [1,2]

Finally, you can extract an array of values selectively based on a list of keys, using the indices method. This works for hashes much as the method of the same name works for arrays (the alias is indexes):

  h = {1=>"one",2=>"two",3=>"three",4=>"four","cinco"=>"five"}
  h.indices(3,"cinco",4)   # ["three","five","four"]
  h.indexes(1,3)       # ["one","three"]

Selecting Key/Value Pairs by Criteria

The Hash class mixes in the Enumerable module, so you can use detect (find), select (find_all), grep, min, max, and reject as with arrays.

The detect method (whose alias is find) finds a single key/value pair. It takes a block (into which the pairs are passed one at a time) and returns the first pair for which the block evaluates to true. Here's an example:

  names = {"fred"=>"jones","jane"=>"tucker",
       "joe"=>"tucker","mary"=>"SMITH"}
  # Find a tucker
  names.detect {|k,v| v=="tucker" }  # ["joe","tucker"]
  # Find a capitalized surname
  names.find {|k,v| v==v.upcase }  # ["mary", "SMITH"]

Of course, the objects in the hash can be of arbitrary complexity, as can the test in the block, but comparisons between differing types can cause problems.

The select method (whose alias is find_all) will return multiple matches, as opposed to a single match:

  names.select {|k,v| v=="tucker" }
  # [["joe", "tucker"], ["jane", "tucker"]]
  names.find_all {|k,v| k.count("r")>0}
  # [["mary", "SMITH"], ["fred", "jones"]]

Sorting a Hash

Hashes are by their nature not ordered according to the value of their keys or associated values. In performing a sort on a hash, Ruby converts the hash to an array and then sorts that array. The result is naturally an array:

  names = {"Jack"=>"Ruby","Monty"=>"Python",
       "Blaise"=>"Pascal", "Minnie"=>"Perl"}
  list = names.sort
  # list is now:
  # [["Blaise","Pascal"], ["Jack","Ruby"],
  # ["Minnie","Perl"], ["Monty","Python"]]

Merging Two Hashes

Merging hashes may be useful sometimes. Ruby's update method will put the entries of one hash into the target hash, overwriting any previous duplicates:

  dict = {"base"=>"foundation", "pedestal"=>"base"}
  added = {"base"=>"non-acid", "salt"=>"NaCl"}
  dict.update(added)
  # {"base"=>"non-acid", "pedestal"=>"base", "salt"=>"NaCl"}

Creating a Hash from an Array

The easiest way to create a hash from an array is to remember the bracket notation for creating hashes. This works if the array has an even number of elements. Here's an example:

  array = [2, 3, 4, 5, 6, 7]
  hash = Hash[*array]
  # hash is now: {2=>3, 4=>5, 6=>7}

Finding Difference or Intersection of Hash Keys

Because the keys of a hash can be extracted as a separate array, the extracted arrays of different hashes can be manipulated using the Array class methods & and - to produce the intersection and difference of the keys. The matching values can be generated with the each method performed on a third hash representing the merge of the two hashes (to ensure all keys can be found in one place):

  a = {"a"=>1,"b"=>2,"z"=>3}
  b = {"x"=>99,"y"=>88,"z"=>77}
  intersection = a.keys & b.keys
  difference = a.keys - b.keys
  c = a.dup.update(b)
  inter = {}
  intersection.each {|k| inter[k]=c[k] }
  # inter is {"z"=>77}
  diff={}
  difference.each {|k| diff[k]=c[k] }
  # diff is {"a"=>1, "b"=>2}

Using a Hash As a Sparse Matrix

Often we want to make use of an array or matrix that is nearly empty. We could store it in the conventional way, but this is often wasteful of memory. A hash provides a way to store only the values that actually exist.

Here is an example in which we are assuming that the nonexistent values should default to zero:

  values = Hash.new(0)
  values[1001] = 5
  values[2010] = 7
  values[9237] = 9
  x = values[9237]   # 9
  y = values[5005]   # 0

Obviously in this example, an array would have created over 9,000 unused elements. This may not be acceptable.

What if we want to implement a sparse matrix of two or more dimensions? All we need do is use arrays as the hash keys, like so:

  cube = Hash.new(0)
  cube[[2000,2000,2000]] = 2
  z = cube[[36,24,36]]    # 0

In this case, we see that literally billions of array elements would need to be created if this three-dimensional array were to be complete.

Implementing a Hash with Duplicate Keys

Purists would likely say that if a hash has duplicate keys, it isn't really a hash. We don't want to argue. Call it what you will, there might be occasions when you want a data structure that offers the flexibility and convenience of a hash but allows duplicate key values.

We offer a partial solution here (see Listing 3.9). It is partial for two reasons. First, we have not bothered to implement all the functionality that could be desired, but only a good representative subset. Second, the inner workings of Ruby are such that a hash literal is always an instance of the Hash class, and even though we were to inherit from Hash, a literal would not be allowed to contain duplicates. (We're thinking about this one further.)

But as long as you stay away from the hash-literal notation, this problem is doable. Here we implement a class that has a "store" (@store) that is a simple hash; each value in the hash is an array. We control access to the hash in such a way that when we find ourselves adding a key that already exists, we add the value to the existing array of items associated with that key.

What should size return? Obviously, the "real" number of key/value pairs including duplicates. Likewise, the keys method returns a value potentially containing duplicates. The iterators behave as expected; as with a normal hash, there is no predicting the order in which the pairs will be visited.

Besides the usual delete, we have implemented a delete_pair method. The former will delete all values associated with a key; the latter will delete only the specified key/value pair. (Note that it would have been difficult to make a single method such as delete(k,v=nil) because nil is a valid value for any hash.)

For brevity, we have not implemented the entire class; frankly, some of the methods, such as invert, would require some design decisions as to what their behavior should be. If you're interested, you can flesh out the rest as needed.

Listing 3.9 Hash with Duplicate Keys

  class HashDup

   def initialize(*all)
    raise IndexError if all.size % 2 != 0
    @store = {}
    if all[0] # not nil
     keyval = all.dup
     while !keyval.empty?
      key = keyval.shift
      if @store.has_key?(key)
       @store[key] += [keyval.shift]
      else
       @store[key] = [keyval.shift]
      end
     end
    end
   end

   def store(k,v)
    if @store.has_key?(k)
     @store[k] += [v]
    else
     @store[k] = [v]
    end
   end

   def [](key)
    @store[key]
   end

   def []=(key,value)
    self.store(key,value)
   end

   def to_s
    @store.to_s
   end

   def to_a
    @store.to_a
   end

   def inspect
    @store.inspect
   end

   def keys
    result=[]
    @store.each do |k,v|
     result += ([k]*v.size)
    end
    result
   end

   def values
    @store.values.flatten
   end

   def each
    @store.each {|k,v| v.each {|y| yield k,y}}
   end

   alias each_pair each

   def each_key
    self.keys.each {|k| yield k}
   end

   def each_value
    self.values.each {|v| yield v}
   end

   def has_key? k
    self.keys.include? k
   end

   def has_value? v
    self.values.include? v
   end

   def length
    self.values.size
   end

   alias size length

   def delete k
    val = @store[k]
    @store.delete k
    val
   end

   def delete k,v
    @store[k] -= [v] if @store[k]
    v
   end

   # Other methods omitted here...

  end



  # This won't work... dup key will ignore
  # first occurrence.
  h = {1=>1, 2=>4, 3=>9, 4=>16, 2=>0}

  # This will work...
  h = HashDup.new(1,1, 2,4, 3,9, 4,16, 2,0)

  k = h.keys     # [4, 1, 2, 2, 3]
  v = h.values    # [16, 1, 4, 0, 9]

  n = h.size     # 5

  h.each {|k,v| puts "#{k} => #{v}"}
  # Prints:
  # 4 => 16
  # 1 => 1
  # 2 => 4
  # 2 => 0

# 3 => 9

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020