Guest User

Untitled

a guest
Jul 23rd, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.97 KB | None | 0 0
  1. # concept of what a hash is doing internally
  2. # This is intended for pedagogy, not actual use
  3. # results will be nondeterministic, and sometimes not work correctly
  4. class HashConcept
  5.  
  6. KEY , VALUE = 0 , 1
  7.  
  8. def initialize
  9. @hash_objects = Array.new 5
  10. end
  11.  
  12. def []=(key,value)
  13. @hash_objects[index key] = [key,value]
  14. end
  15.  
  16. def [](key)
  17. hashobj = @hash_objects[index key]
  18. return nil unless hashobj && hashobj[KEY] == key
  19. hashobj[VALUE]
  20. end
  21.  
  22. def index(key)
  23. key.hash.abs % @hash_objects.size
  24. end
  25.  
  26. def inspect
  27. @hash_objects.inspect
  28. end
  29.  
  30. end
  31.  
  32.  
  33. my_hash = HashConcept.new
  34.  
  35. # can add and remove values based on a key
  36. my_hash['a'] = 1
  37. my_hash # => [nil, nil, ["a", 1], nil, nil]
  38. my_hash['a'] # => 1
  39.  
  40. # how did it know to store it in that index?
  41. 'a'.hash.abs % 5 # => 2
  42.  
  43. # can add more values
  44. my_hash[12] = :my_fav_num
  45. my_hash # => [[12, :my_fav_num], nil, ["a", 1], nil, nil]
  46.  
  47. # nonexistent keys return nil
  48. my_hash[:not_a_real_key] # => nil
Add Comment
Please, Sign In to add comment