Photo by Alessandro Cattelan from FreeImages
Welcome back! I bet you're ready to dig a bit deeper into our awesome bookshelf hash. We are going to take a closer look at accessing information from a variety of nested data structure types.
Let's get started by checking out that lovely hash again:
By now you should be pretty familiar with the primary keys and the data type of the values each key returns. If not, no biggie! Just go back to part one and browse around a bit longer- sometimes it takes a moment for new concepts to really soak into that amazing brain. It's ok.
Run the repl.it below to see how to work further with this hash.
Take some time to review the code for each example, noting how to access the desired values. We will go over each example in more detail below.
1. Print the value of shelf one, a string, in uppercase:
This really just builds off of what we went over in the first post. Access the value of ':shelf_one' directly and convert that string to uppercase.
bookshelf[:shelf_one].upcase => "ENCYCLOPEDIAS"
2. Access the value of shelf two, an array, and print the last element:
Here we are grabbing the value of ':shelf_two', an array, and returning the last element.
bookshelf[:shelf_two].last => "Star Atlas"
3. Print each item in the array from shelf two:
Using the same array from example 2 above, puts each element out to the user. Note that the return value is the original array since we used '.each'.
bookshelf[:shelf_two].each {|b| puts b} => ["World Maps", "Star Atlas"]
Puts out to the user:
World Maps
Star Atlas
4. Print each key/value pair in the hash from shelf three:
The value of bookshelf[:shelf_three] is a hash, this example shows how to puts each key/value pair out to the user. Return value is the original hash.
bookshelf[:shelf_three].each do |k,v|
puts "#{k}: #{v}"
end
=> {:sci_fi=>"The Collection", :coloring_books=>"Mandalas"}
Puts out to the user:
sci_fi: The Collection
coloring_books: Mandalas
5. Iterate over the hash of arrays from shelf four and list the key along with each value:
The value for the ':shelf_four' key is an array, and for this example the goal is to puts out to the user each element of the array as a value of the secondary key ':sci_fi'. For this to work, we must take an additional step to grab each value and put it out to the user along with the key. As you may have guessed, the return value is the original value itself.
bookshelf[:shelf_four].each do |k,v|
v.each do |v|
puts "#{k}: #{v}"
end
end
=> {:sci_fi=>["The Collection Two", "Fantasy"]}
Puts out to the user:
sci_fi: The Collection Two
sci_fi: Fantasy
As you can see, working with hashes and nested data structures isn't as scary as it seems. Analyze each layer, take it step by step, and don't be afraid to play around with the structure to grab and manipulate data as you wish.
See you next time for the third and final part in this series!
Top comments (0)