File tree 1 file changed +13
-9
lines changed
1 file changed +13
-9
lines changed Original file line number Diff line number Diff line change @@ -4,18 +4,22 @@ class HashTable
4
4
attr_reader :hash
5
5
6
6
def initialize ( size = 500 )
7
- @hash = Array . new
7
+ @hash = Array . new ( size ) { [ ] }
8
8
@size = size
9
9
end
10
10
11
11
def put ( key , value )
12
12
idx = calculate_hash ( key )
13
- @hash [ idx ] = value
13
+ @hash [ idx ] << [ key , value ]
14
14
end
15
15
16
16
def get ( key )
17
17
idx = calculate_hash ( key )
18
- @hash [ idx ]
18
+
19
+ bucket = @hash [ idx ]
20
+ pair = bucket . find { |pair | pair [ 0 ] == key }
21
+
22
+ pair [ 1 ] if pair
19
23
end
20
24
21
25
def delete ( key )
@@ -31,11 +35,11 @@ def calculate_hash(str)
31
35
end
32
36
33
37
hash = HashTable . new
34
- hash . put ( :name , "Jane " )
35
- hash . put ( :age , 22 )
38
+ hash . put ( :code , "ABC123 " )
39
+ hash . put ( :mode , "dark" )
36
40
37
- puts hash . get ( :name ) # => Jane
38
- puts hash . get ( :age ) # => 22
41
+ puts "Code is #{ hash . get ( :code ) } " # => ABC123
42
+ puts "Mode is #{ hash . get ( :mode ) } " # => "dark
39
43
40
- hash . delete ( :name )
41
- puts hash . get ( :name ) # => nil
44
+ hash . delete ( :code )
45
+ puts hash . get ( :code ) # => nil
You can’t perform that action at this time.
0 commit comments