Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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
Add Comment
Please, Sign In to add comment