gpt4 book ai didi

ruby : can't understand memory address

转载 作者:行者123 更新时间:2023-12-04 02:32:51 26 4
gpt4 key购买 nike

当我研究 clone vs dup 时,我尝试复制如下对象:

a = {'key1' => 1, 'key2' => {'key3' => 3, 'key4' => 4}}.freeze
b = a.clone
c = a.dup

a['key1'] = 32
# => RuntimeError: can't modify frozen Hash

b['key1'] = 32
# => RuntimeError: can't modify frozen Hash

c['key1'] = 32
# => 32

大写结果,a和b值共享内存但是,当我检查变量 object_id 时,它返回不同的结果:

a.object_id ## original
=> 70219554622880
b.object_id ## clone
=> 70219554589820

但在哈希键中 object_id 是相同的。

a['key1'].object_id ## original
=> 3
b['key1'].object_id ## clone
=> 3
c['key1'].object_id ## dup
=> 65

我不明白 a 和 b 变量不匹配 object_id,但在哈希键中 object_id 是相同的。

您能给我您的想法、答案或意见吗?谢谢。

最佳答案

您可能会特别感到困惑,因为您使用的是整数。 Ruby 中的整数是单例:它们的整数值决定了它们的对象 ID。

x = 3
y = 3
x.object_id == y.object_id # true
x = "a"
y = "a"
x.object_id == y.object_id # false

然而,这仅适用于达到特定大小的整数。

x = 11111111111111111111111111111111
y = 11111111111111111111111111111111
x.object_id == y.object_id # false

这是因为如果整数值足够小,Ruby 实际上会将整数值存储在对象 ID 中。如果数字太大,则必须分配一个新对象。

关于 ruby : can't understand memory address,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63183179/

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