Hash tables / hash maps in Ruby


Created by Stan on 09-04-2023


A hash table, also known as a hash map or dictionary, is a data structure that allows you to store and retrieve values based on a unique key. It is widely used in various applications, including implementing symbol tables in compilers, storing configuration settings, and caching data for faster retrieval.

In this article, we will delve into the world of hash tables and learn how to work with them in Ruby. We will discuss key operations associated with hash tables, demonstrate the usage of Ruby's built-in Hash class, and explore practical use cases for hash tables in Ruby.

A hash table supports four primary operations:

insert: Add a key-value pair to the hash table.
delete: Remove a key-value pair from the hash table.
lookup: Retrieve the value associated with a given key.
contains?: Check if the hash table contains a specific key.

Ruby's built-in hash class

Ruby has a built-in Hash class that provides an efficient and easy-to-use implementation of hash tables. Here's an example of how to create and manipulate a hash table using Ruby's Hash class:

# Creating a new hash table
hash_table = Hash.new

# Inserting key-value pairs
hash_table[:name] = "Alice"
hash_table[:age] = 30
hash_table[:city] = "New York"

# Deleting a key-value pair
hash_table.delete(:city)

# Looking up a value by its key
puts "Name: #{hash_table[:name]}" #=> Name: Alice

# Checking if a key exists in the hash table
puts "Contains :city? #{hash_table.key?(:city)}" #=> Contains :city? false

Examples of hash table usage

Counting word frequencies

Hash tables can be used to efficiently count the frequency of words in a given text. Here's a Ruby function that uses a hash table to achieve this:

def word_frequencies(text)
  frequencies = Hash.new(0)
  words = text.downcase.split

  words.each do |word|
    frequencies[word] += 1
  end

  frequencies
end

text = "This is a test. This is only a test."
frequencies = word_frequencies(text)
puts frequencies #=> {"this"=>2, "is"=>2, "a"=>2, "test."=>1, "only"=>1, "test."=>1}

Implementing a simple cache

Hash tables can be used to implement a simple cache for storing and retrieving data quickly. Here's an example of a basic cache implementation using a hash table:

class SimpleCache
  def initialize
    @storage = Hash.new
  end

  def store(key, value)
    @storage[key] = value
  end

  def fetch(key)
    @storage[key]
  end

  def delete(key)
    @storage.delete(key)
  end

  def contains?(key)
    @storage.key?(key)
  end
end

cache = SimpleCache.new
cache.store(:result, 42)
puts cache.fetch(:result) #=> 42

Storing configuration settings

Hash tables are useful for storing configuration settings in an application. Here's a simple example of using a hash table to store and retrieve settings:

config = {
  app_name: "MyApp",
  database: {
    host: "localhost",
    port: 5432,
    username: "user",
    password: "password"
  },
  log_level: "info"
}

puts "App name: #{config[:app_name]}" #=> App name: MyApp
puts "Database host: #{config[:database][:host]}" #=> Database host: localhost

config[:log_level] = "debug"
puts "Log level: #{config[:log_level]}" #=> Log level: debug

config[:cache_timeout] = 300
puts "Cache timeout: #{config[:cache_timeout]}" #=> Cache timeout: 300

In this example, we use a hash table with nested hashes to store configuration settings for an application. This allows us to easily access and modify settings in a structured manner.

The examples provided in this article are just the beginning, and there are countless other use cases for hash tables in Ruby and other programming languages. It is a good idea to keep hash tables in mind when faced with problems that require organizing and manipulating data based on keys.



Related Posts

Interviews

Posted on 08 Apr, 2023
Linked list in Ruby

Interviews

Posted on 09 Apr, 2023
Queues in Ruby