2017-01-20 45 views
3

another answer讀它最好使用array.map(&:dup)差(:DUP)`

不要使用編組伎倆,除非你真的很想複製整個對象圖。通常你只想複製數組而不是包含的元素。

很想看到一個例子來說明這兩種方法之間的區別。

除了我看起來像他們正在做同樣的事情的語法。

很想了解更多關於Marshal#dup之間的區別。

arr = [ [['foo']], ['bar']] 
    foo = arr.clone 
    p arr #=> [[["foo"]], ["bar"]] 
    p foo #=> [[["foo"]], ["bar"]] 
    foo[0][0] = 42 
    p arr #=> [[42], ["bar"]] 
    p foo #=> [[42], ["bar"]] 

    arr = [ [['foo']], ['bar']] 
    foo = Marshal.load Marshal.dump arr 
    p arr #=> [[["foo"]], ["bar"]] 
    p foo #=> [[["foo"]], ["bar"]] 
    foo[0][0] = 42 
    p arr #=> [[["foo"]], ["bar"]] 
    p foo #=> [[42], ["bar"]] 

    arr = [ [['foo']], ['bar']] 
    foo = arr.map(&:dup) 
    p arr #=> [[["foo"]], ["bar"]] 
    p foo #=> [[["foo"]], ["bar"]] 
    foo[0][0] = 42 
    p arr #=> [[["foo"]], ["bar"]] 
    p foo #=> [[42], ["bar"]] 
+1

'array.map(&:dup)'很好,因爲map無論如何創建一個副本,額外的dup是我的其他答案中的拼寫錯誤 – akuhn

回答

0

元帥伎倆也克隆數組的元素

array = [[Object.new]] 

元素的檢查object_id前和副本

array.first.first.object_id 
# => 70251489489120 

array.map(&:dup).first.first.object_id 
# => 70251489489120 -- the same 

(Marshal.load Marshal.dump array).first.first.object_id 
# => 70251472965580 -- different object! 

不要使用編組招除非你以後真的很想複製整個對象圖。通常你只想複製數組而不是包含的元素。