1

dup是浅拷贝,所以这样做时:

h = {one: {a:'a', b: 'b'}}
h_copy = h.dup
h_copy[:one][:b] = 'new b'

现在hh_copy一样:{:one=>{:a=>"a", :b=>"new b"}} 是的,没错。

但是什么时候h是一维哈希:

h = {a:'a', b: 'b'}
h_copy = h.dup
h_copy[:b] = 'new b'
h still is: {a:'a', b: 'b'}
h_copy is {a:'a', b: 'new b'}

为什么?

4

3 回答 3

3

您可以将二维散列视为某种容器,其中包含另一个散列容器。所以你有2个容器。

当您调用dupon 时h,然后dup返回您最外层容器的副本,但不会复制任何内部容器,所以这就是浅拷贝所做的。现在在 dup 之后你有3 个容器:h_copy是你新的第三个容器,它的:one键只指向h的内部容器

于 2012-11-19T08:10:00.863 回答
0

正如你所说,dup是浅拷贝。

看来您想要两者h_copyh引用同一个对象。

然后简单地做h_copy = h(即不dup)。

h = {a:'a', b: 'b'}
h_copy = h.dup
h_copy[:b] = 'new b'
h #=> {a:'a', b: 'new b'}
于 2012-11-19T06:36:40.267 回答
-1

所以经过 1 小时的头脑风暴..我得出的结论是,在多维散列中,dup 为每个键生成相同的 object_id,而在单维散列中,object_ids 最初是相似的但是当我们对对象进行任何更改时,Ruby 会将新的 object_id 分配给哈希键。

看下面的代码

h = { :a => "a", :b => "b" } # => {:a=>"a", :b=>"b"} 
h_clone = h.dup #=> {:a=>"a", :b=>"b"} 
h.object_id #=> 73436330 
h_clone.object_id #=> 73295920 
h[:a].object_id #=> 73436400 
h_clone[:a].object_id #=> 73436400 
h[:b].object_id #=> 73436380 
h_clone[:b].object_id #=> 73436380 
h_clone[:b] = "New B" #=> "New B" 
h_clone[:b].object_id #=> 74385280 
h.object_id #=> 73436330 
h_clone.object_id #=> 73295920 
h[:a].object_id #=> 73436400 
h_clone[:a].object_id #=> 73436400

查看多维数组的以下代码

h = { :one => { :a => "a", :b => "b" } } #=> {:one=>{:a=>"a", :b=>"b"}} 
h_copy = h.dup #=> {:one=>{:a=>"a", :b=>"b"}} 
h_copy.object_id #=> 80410620 
h.object_id #=> 80552610 
h[:one].object_id #=> 80552620 
h_copy[:one].object_id #=> 80552620 
h[:one][:a].object_id #=> 80552740 
h_copy[:one][:a].object_id #=> 80552740 
h[:one][:b].object_id #=> 80552700 
h_copy[:one][:b].object_id #=> 80552700 
h_copy[:one][:b] = "New B" #=> "New B" 
h_copy #=> {:one=>{:a=>"a", :b=>"New B"}} 
h #=> {:one=>{:a=>"a", :b=>"New B"}} 
h.object_id #=> 80552610 
h_copy.object_id #=> 80410620 
h[:one].object_id #=> 80552620 
h_copy[:one].object_id #=> 80552620 
h[:one][:b].object_id #=> 81558770 
h_copy[:one][:b].object_id #=> 81558770
于 2012-11-19T08:23:10.080 回答