DEV Community

Cover image for Hash-tastic! part three
Leigha
Leigha

Posted on

Hash-tastic! part three

Photo by Joel Dietle from FreeImages

Hello again! I hope that so far you are learning to appreciate hashes and the power of nested data structures. Let's take a final look at our awesome bookshelf hash. In case you've forgotten what it looks like, parts 1 & 2 of this series have a lovely image for review.

This time we'll be working with the last shelf, the Harry Potter bookshelf, a hash of hashes. We will go over how to output data from within this structure that is itself nested within the parent hash bookshelf.

The desired output in this example is a sentence that displays to the user the book number (1st level key) and title (2nd level key) of every volume within the ':harry_potter' shelf.

Run the repl.it below to see how it works.

Here is a closer look at the magic that makes it happen:

def print_potter_books(shelf)
  shelf.each do |volume, info|
    info.each do |k, v|
      if k == :title 
        puts "The title of #{name(volume)} is #{v}."
        sleep(2)
      end
    end  
  end
end
print_potter_books(bookshelf[:harry_potter])
Enter fullscreen mode Exit fullscreen mode

Here we take the ':harry_potter' shelf, iterate over it, taking each volume, which contains info, and then iterating over that info, making a comparison against each key inside the info and if it matches, outputting the desired text containing data from two different layers of the hash.

NOTE: The name method can be found on line 44 in the repl.it

Whew! If that was a bit much, just take a moment to read the code line by line. Try to think about the nested data structure like an onion and just peel away at it one layer at a time.

For example, the code to show the user the date for Book 7 looks like this:

puts bookshelf[:harry_potter][:book_7][:date]
Enter fullscreen mode Exit fullscreen mode

Puts out to the user:
2007

Here it is easy to see the different levels of the data structure. The parent hash is bookshelf and to get to the date you must reach down three levels.

Thanks for reading this far. If you didn't already know how awesome hashes and nested data structures are, hopefully now you do (at least a little bit)!

Top comments (0)