gpt4 book ai didi

ruby - 哈希中更改的数组键的行为

转载 作者:数据小太阳 更新时间:2023-10-29 07:53:14 25 4
gpt4 key购买 nike

Ruby 允许将可变对象用作散列键,我很好奇对象更新时它是如何工作的。如果引用的对象已更新,则似乎无法从关键请求中检索到它。

key = [1,2]
test = {key => 12}

test # => {[1, 2] => 12}
test[key] # => 12
test[[1,2]] # => 12
test[[1,2,3]] # => nil

key << 3

test # => {[1, 2, 3] => 12}
test[key] # => nil
test[[1,2]] # => nil
test[[1,2,3]] # => nil

为什么会这样?为什么我不能为散列提供一个键,该键将返回与我最初用作键的列表关联的值?

最佳答案

根据 the documentation :

Two objects refer to the same hash key when their hash value is identical and the two objects are eql? to each other.

更改 key 不会更改存储它的哈希值。更改 key 后,尝试使用 [1,2] 进行索引匹配 hash 但不匹配 eql?,而 [1 ,2,3]eql? 匹配,但未通过 hash 找到。

参见 this article以获得更详细的解释。

但是,您可以重新散列test,以根据当前键值重新计算散列:

test.rehash
test[[1,2,3]] # => 12

关于ruby - 哈希中更改的数组键的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16802165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com