Lesson 3
Exploring Hashes in Ruby
Exploring Hashes in Ruby

Hello again! This lesson's topic is Ordered Hashes. Similar to Hashes, Ordered Hashes are data structures that store key-value pairs but maintain the order of insertion. Learning about Ordered Hashes enriches our set of tools for organized and efficient data manipulation. Today's goal is to work with Ordered Hashes using Ruby's built-in Hash class, which maintains insertion order.

Introduction: Hashes and Ordered Hashes in Ruby

Hashes in Ruby are collections of key-value pairs, where each key is unique. They are versatile data structures, allowing various operations such as insertion, deletion, and retrieval based on the keys.

In Ruby all Hashes inherently maintain the order of elements based on their insertion sequence. The standard Hash now provides this behavior in newer Ruby versions, making a distinct data structure for sorting the items in order unnecessary.

Discovering Ordered Hashes

To create an Ordered Hash, you simply need to create a standard Hash. For instance:

Ruby
1# Hash with fruits as keys and corresponding counts as values 2oh = {'banana' => 3, 'apple' => 4, 'pear' => 1, 'orange' => 2} 3 4# Print the Ordered Hash 5puts oh # Output: {"banana"=>3, "apple"=>4, "pear"=>1, "orange"=>2}
Custom Sorting

While Ruby's ordered hashes maintain elements in their insertion order, you may sometimes need to sort your hash according to custom criteria. You can accomplish this by using the sort or sort_by method, which allows you to sort hash elements based on specific logic.

Here's an example demonstrating how to sort an ordered hash by its keys in ascending order:

Ruby
1# Initialize Ordered Hash 2oh = {'banana' => 3, 'apple' => 4, 'pear' => 1, 'orange' => 2} 3 4# Sort hash by keys in ascending order 5sorted_oh = oh.sort.to_h 6 7# Print the custom sorted hash 8puts sorted_oh # Output: {"apple"=>4, "banana"=>3, "orange"=>2, "pear"=>1}

In this example, the sort method sorts each key-value pair based on the keys since it's the default behavior of sort when applied directly to a hash. The resulting array of pairs is then converted back to a hash using to_h to preserve the hash structure.

Traversing Ordered Hash Methods

An Ordered Hash in Ruby provides several useful methods common to all Hashes. Here are some crucial ones:

  • oh.keys: This returns an array of all keys in the hash.
  • oh.values: This returns an array of all values in the hash.
  • oh.delete(key): This removes a specified key and returns its associated value.
  • oh.fetch(key, default): This retrieves the value for the key if it exists; otherwise, it returns a default value.
  • oh.each: This method allows you to iterate over each key-value pair in the hash, in their insertion order.

Consider the following Ruby code, which incorporates these methods:

Ruby
1# Initialize Ordered Hash 2oh = {'banana' => 3, 'apple' => 4, 'pear' => 1, 'orange' => 2} 3 4# Print all keys 5puts oh.keys # Output: ["banana", "apple", "pear", "orange"] 6 7# Print all values 8puts oh.values # Output: [3, 4, 1, 2] 9 10# Remove 'apple' and print the removed item 11item = oh.delete('apple') 12puts "Deleted item: #{item}" # Output: Deleted item: 4 13 14# Attempt to fetch a nonexisting key 15value = oh.fetch('apple', 'Not found') 16puts "Value: #{value}" # Output: Value: Not found 17 18# Iterate over each key-value pair 19oh.each do |key, value| 20 puts "#{key}: #{value}" 21end 22# Output: 23# banana: 3 24# pear: 1 25# orange: 2
Lesson Summary

Congratulations! You have successfully delved into ordered hashes in Ruby. This exploration included understanding the inherent behavior of Ruby's Hash class to maintain insertion order, creating ordered hash instances, and navigating their useful methods. Next, you can look forward to hands-on exercises to fortify your understanding and expand your skill set. Keep practicing!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.