Created
February 23, 2011 07:33
-
-
Save JoshCheek/840135 to your computer and use it in GitHub Desktop.
about as simple of a hash implementation as you could get
This file contains 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
# concept of what a hash is doing internally | |
# This is intended for pedagogy, not actual use | |
# results will be nondeterministic, and sometimes not work correctly | |
class HashConcept | |
KEY , VALUE = 0 , 1 | |
def initialize | |
@hash_objects = Array.new 5 | |
end | |
def []=(key,value) | |
@hash_objects[index key] = [key,value] | |
end | |
def [](key) | |
hashobj = @hash_objects[index key] | |
return nil unless hashobj && hashobj[KEY] == key | |
hashobj[VALUE] | |
end | |
def index(key) | |
key.hash.abs % @hash_objects.size | |
end | |
def inspect | |
@hash_objects.inspect | |
end | |
end | |
my_hash = HashConcept.new | |
# can add and remove values based on a key | |
my_hash['a'] = 1 | |
my_hash # => [nil, nil, ["a", 1], nil, nil] | |
my_hash['a'] # => 1 | |
# how did it know to store it in that index? | |
'a'.hash.abs % 5 # => 2 | |
# can add more values | |
my_hash[12] = :my_fav_num | |
my_hash # => [[12, :my_fav_num], nil, ["a", 1], nil, nil] | |
# nonexistent keys return nil | |
my_hash[:not_a_real_key] # => nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment