简体   繁体   中英

Why can't I put a hash inside itself as a key?

I can use hashes as keys and values:

a = {}
b = {}
a[b] = b
a          #=> {{}=>{}}
a[b] == b  #=> true

I can even put a hash inside itself as a value:

a[:a] = a
a          #=> {{}=>{}, :a=>{...}}
a == a[:a] #=> true

But I can't put a hash inside itself as a key:

a[a] = a
a          #=> {{}=>{}, {...}=>{...}}
a[a]       #=> nil
a[a] == a  #=> false

I would expect a == a[a] #=> true in this case.

Why does this happen? I don't have a use case for this, I'm just curious about why a hash can't be used as it's own key.

It is not that you cannot. You just need to rehash after you modify a mutable key in the hash.

a = {}
b = {}
a[b] = b
a[:a] = a
a[a] = a

a.rehash
# => {{}=>{}, :a=>{...}, {...}=>{...}}
a[a] == a
# => true

The a is different before and after a[a] = a . So you needed to update the a key of a .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM