This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.
| Using an Array or Other Modifiable Object as a Hash Key | ||
|---|---|---|
| Code | Expected | Actual |
coordinates = [10, 5]
treasure_map = { coordinates => 'jewels' }
treasure_map[coordinates] |
"jewels" | "jewels" |
coordinates << -5 coordinates |
[10, 5, -5] | [10, 5, -5] |
treasure_map[coordinates] |
nil | nil |
treasure_map.rehash treasure_map[coordinates] |
"jewels" | "jewels" |
module ReliablyHashable
def hash
return object_id
end
end
class ReliablyHashableArray < Array
include ReliablyHashable
end
coordinates = ReliablyHashableArray.new([10,5])
treasure_map = { coordinates => 'jewels' }
treasure_map[coordinates] |
"jewels" | "jewels" |
coordinates.push(-5) treasure_map[coordinates] |
"jewels" | "jewels" |
a = [1,2] b = a.clone a.hash |
11 | 11 |
b.hash |
11 | 11 |
a = ReliablyHashableArray.new([1,2]) b = a.clone a.hash |
-606031406 | -606028286 |
b.hash |
-606034266 | -606031146 |