Philip M
Philip M

Reputation: 149

Putting a Hashmap into itself causes strange behavior

The following code creates a hashmap and places it inside of itself.

hash = {}
hash[hash] = hash
hash.keys.first == hash # true
hash.values.first == hash # true
hash[hash] # nil??
hash.key?(hash) # False
hash[hash.keys.first] # nil???
hash[{}] # nil

Can anyone explain these results to me? They seem very counterintuitive.

Upvotes: 4

Views: 50

Answers (1)

Tom Lord
Tom Lord

Reputation: 28305

Mutable objects (such as Array and Hash) are basically improper for a hash key if you may modify them. In this case, the hash was modified at the point of insertion (since it was inserted into itself!) and has therefore been left in an improper state.

If it is absolutely necessary, you can use Hash#rehash to rectify the object state:

hash = {}
hash[hash] = hash

hash.rehash # !!!!

hash.keys.first == hash # true
hash.values.first == hash # true
hash[hash] #=> {{...}=>{...}}
hash.key?(hash) # true
hash[hash.keys.first] #=> {{...}=>{...}}
hash[{}] # nil

Upvotes: 5

Related Questions