Last active
December 28, 2017 06:59
-
-
Save arjans/db79d5ba3b644fd41b197a882b2b5ee1 to your computer and use it in GitHub Desktop.
Hash Table Implementation in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Meant to work with strings as keys. | |
class MyHash | |
def initialize(size: 100) | |
@size = size | |
@hash = Array.new(size) | |
end | |
attr_accessor :hash | |
def insert(key, value) | |
i = hashing_function(key) | |
@hash[i] ||= [] | |
if @hash[i].find { |arr| arr.first == key } | |
return "Key exists." | |
else | |
@hash[i] << [key, value] | |
end | |
end | |
def delete(key) | |
i = hashing_function(key) | |
arr = lookup(key) | |
@hash[i].delete(arr) | |
end | |
def lookup(key) | |
i = hashing_function(key) | |
if @hash[i] | |
result = @hash[i].find { |arr| arr.first == key } | |
else | |
nil | |
end | |
result | |
end | |
def hashing_function(key) | |
key.chars.map(&:ord).reduce(&:*) % @size | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment