Recipe 5.5. Using an Array or Other Modifiable Object as a Hash KeyProblemYou want to use a modifiable built-in object (an array or a hash, but not a string) as a key in a hash, even while you modify the object in place. A naive solution tends to lose hash values once the keys are modified:
SolutionThe easiest solution is to call the
If this is too much code, you might consider changing the definition of the object you use as a hash key, so that modifications don't affect the way the hash treats it. Suppose you want a reliably hashable Array class. If you want this behavior universally, you can reopen the Array class and redefine hash to give you the new behavior. But it's safer to define a subclass of Array that implements a reliable-hashing mixin, and to use that subclass only for the
It's now possible to keep track of the jewels:
DiscussionRuby performs hash lookups using not the key object itself but the object's hash code (an integer obtained from the key by calling its hash method). The default implementation of hash, in Object, uses an object's internal ID as its hash code. Array, Hash, and String override this method to provide different behavior. In the initial example, the hash code of [10,5] is 41 and the hash code of [10,5,5] is83. The mapping of the coordinate list to 'jewels' is still present (it'll still show up in an iteration over each_pair), but once you change the coordinate list, you can no longer use that variable as a key. You may also run into this problem when you use a hash or a string as a hash key, and then modify the key in place. This happens because the hash implementations of many built-in classes try to make sure that two objects that are "the same" (for instance, two distinct Because of the potential for confusion, some languages don't let you use arrays or hashes Since an object's internal ID never changes, the Object implementation is what you want to get reliable hashing. To get it back, you'll have to override or subclass the hash method of Array or Hash (depending on what type of key you're having trouble with). The implementations of hash given in the solution violate the principle that different representations of the same data should have the same hash code. This means that two ReliablyHashableArray objects will have different
If you want a particular value in a hash to be accessible by two different Another solution is to freeze your See Also
|
Monday, November 2, 2009
Recipe 5.5. Using an Array or Other Modifiable Object as a Hash Key
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment