Hash Tables
A hash table is a data structure that stores key-value pairs. It uses a hash function to compute an index into an array where the desired value can be found. Hash tables offer efficient lookup, insertion, and deletion operations.
Below is the Ruby program to implement hash tables:
class HashTable
def initialize(size)
@size = size
@table = Array.new(size)
end
def put(key, value)
index = hash(key)
@table[index] = value
end
def get(key)
index = hash(key)
@table[index]
end
private
def hash(key)
key.hash % @size
end
end
# Example Usage
hash_table = HashTable.new(5)
hash_table.put(:apple, "A fruit")
hash_table.put(:banana, "Another fruit")
puts hash_table.get(:apple) # Output: "A fruit"
puts hash_table.get(:banana) # Output: "Another fruit"
Output:
How to Implement Data Structures in Ruby?
Data structures are fundamental components of any programming language, allowing developers to organize and manipulate data efficiently. In Ruby, a versatile and expressive language, implementing various data structures is straightforward. In this article, we’ll explore how to implement common data structures such as arrays, linked lists, stacks, queues, trees, graphs, and hashmaps in Ruby. The article focuses on discussing data structures in Ruby.
Table of Content
- Singly-Linked Lists
- Doubly-Linked Lists
- Circular Linked Lists
- Queues
- Stack
- Hash Tables
- Sets
- Binary Trees
- AVL Trees (Adelson-Velsky and Landis Trees)
- Graphs
- Persistent Lists
Contact Us