For instance,
s1 = Student.new(1, "Bob", "Podunk High")
hash[1] = s1
puts hash[1].name #produces "Bob"
s1.id = 15
puts hash[15].name #produces "Bob"
puts hash[1].name #fails
This is not exactly Hash-like behavior and insertions with the wrong key still needs to be defined.
While I can certainly roll my own container that behaves this way but it will be hard to make it fast, ie not search through the whole container every time [] is called. Just wondering if someone smarter has already made something I can steal.
EDIT: Some good ideas below helped me focus my requirements:
-
avoid the O(n) lookup time
-
allow multiple containers to the same object (association not composition)
-
have different data types (eg. that might use
nameinstead ofid) without too much reimplementation
You can implement it yourself.
Look at the draft solution:
Or you can play around Array class (or Hash, if you really need it):
etc
And after @tadman’s correct comment you can use reference to your
hashright into your Student class: