Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created February 23, 2011 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoshCheek/840135 to your computer and use it in GitHub Desktop.
Save JoshCheek/840135 to your computer and use it in GitHub Desktop.
about as simple of a hash implementation as you could get
# 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