2017-01-20 4 views
3

私はarray.map(&:dup)を使用するのが好ましいですanother answerで読む:違い `

ますしない限り、マーシャリングのトリックを使用しないでください。本当にオブジェクトグラフ全体を深くコピーしたいと思っています。通常、配列のみをコピーしたいのですが、含まれている要素はコピーしません。

これらの2つの方法の違いを示す例が好きです。

構文以外にも、同じことをしているように見えます。

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)'は十分です。マップはコピーを作成するので、追加のdupは私の他の答えのタイプミスです – akuhn

答えて

0

マーシャルトリックはまた、あなたがない限りマーシャリングのトリックを使用しないでくださいコピー

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! 

の前と後の要素の配列

array = [[Object.new]] 

チェックobject_idの要素のクローン本当にオブジェクトグラフ全体を深くコピーしたいと思っています。通常、配列のみをコピーしたいのですが、含まれている要素はコピーしません。