forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhash_table.rb
45 lines (33 loc) · 773 Bytes
/
hash_table.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# frozen_string_literal: true
class HashTable
attr_reader :hash
def initialize(size = 500)
@hash = Array.new(size) { [] }
@size = size
end
def put(key, value)
idx = calculate_hash(key)
@hash[idx] << [key, value]
end
def get(key)
idx = calculate_hash(key)
bucket = @hash[idx]
pair = bucket.find { |pair| pair[0] == key }
pair[1] if pair
end
def delete(key)
idx = calculate_hash(key)
@hash.delete_at(idx)
end
private
def calculate_hash(str)
str.to_s.bytes.reduce(&:*) % @size
end
end
hash = HashTable.new
hash.put(:code, "ABC123")
hash.put(:mode, "dark")
puts "Code is #{hash.get(:code)}" # => ABC123
puts "Mode is #{hash.get(:mode)}" # => "dark
hash.delete(:code)
puts hash.get(:code) # => nil