0
0
RubyHow-ToBeginner · 3 min read

How to Implement Hash Table in Ruby: Simple Guide

In Ruby, a hash table is implemented using the built-in Hash class, which stores key-value pairs. You create a hash with {} or Hash.new, then add or access values by keys using hash[key] = value and hash[key].
📐

Syntax

A Ruby hash table uses the Hash class to store data as key-value pairs. You can create a hash using curly braces {} or the Hash.new method. Keys and values can be any object. Access or assign values using square brackets hash[key].

  • Creating: hash = { key1 => value1, key2 => value2 }
  • Accessing: hash[key1] returns value1
  • Adding/Updating: hash[new_key] = new_value
ruby
hash = { "apple" => "red", "banana" => "yellow" }
puts hash["apple"]  # Outputs: red
hash["grape"] = "purple"
puts hash["grape"]  # Outputs: purple
Output
red purple
💻

Example

This example shows how to create a hash table, add key-value pairs, access values, and update an existing key.

ruby
fruits = Hash.new
fruits["apple"] = "green"
fruits["banana"] = "yellow"
puts fruits["apple"]  # green
fruits["apple"] = "red"
puts fruits["apple"]  # red
puts fruits["orange"]  # nil (key not found)
Output
green red nil
⚠️

Common Pitfalls

Common mistakes include:

  • Using symbols and strings inconsistently as keys, which are different keys.
  • Expecting a default value when accessing a missing key without setting one.
  • Modifying a default value object shared across keys unintentionally.

Always be consistent with key types and set default values carefully.

ruby
hash = Hash.new([])  # Default is the same array for all missing keys
hash[:a] << 1
hash[:b] << 2
puts hash[:a].inspect  # Outputs: [1, 2] (unexpected sharing)

# Correct way:
hash = Hash.new { |h, k| h[k] = [] }
hash[:a] << 1
hash[:b] << 2
puts hash[:a].inspect  # Outputs: [1]
puts hash[:b].inspect  # Outputs: [2]
Output
[1, 2] [1] [2]
📊

Quick Reference

Ruby Hash Table Quick Tips:

  • Create with {} or Hash.new
  • Use consistent key types (symbols or strings)
  • Access with hash[key], assign with hash[key] = value
  • Set default values with Hash.new(default) or block for mutable defaults

Key Takeaways

Use Ruby's built-in Hash class to implement hash tables easily.
Always be consistent with key types to avoid unexpected behavior.
Set default values carefully to prevent shared mutable objects.
Access and assign values using square brackets with keys.
Use blocks with Hash.new for safe default mutable values.