Skip to content

Instantly share code, notes, and snippets.

@arjans
Last active December 28, 2017 06:59
Show Gist options
  • Save arjans/db79d5ba3b644fd41b197a882b2b5ee1 to your computer and use it in GitHub Desktop.
Save arjans/db79d5ba3b644fd41b197a882b2b5ee1 to your computer and use it in GitHub Desktop.
Hash Table Implementation in Ruby
# 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