Created
November 4, 2010 17:31
-
-
Save yoggy/662822 to your computer and use it in GitHub Desktop.
Rubyのclone,dupはshallow copyなのではまる例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
# | |
# Rubyのclone,dupはshallow copyなのではまる例 | |
# 完全な複製を作るときはMarshal.load(Marshal.dump(コピー対象))を使う | |
# | |
# $ ruby copy_test.rb | |
# == case 1 == | |
# [[[200, 201, 202], [210, 211, 212], [220, 221, 222]], | |
# [[200, 201, 202], [210, 211, 212], [220, 221, 222]], | |
# [[200, 201, 202], [210, 211, 212], [220, 221, 222]]] | |
# == case 2 == | |
# [[[0, 1, 2], [10, 11, 12], [20, 21, 22]], | |
# [[100, 101, 102], [110, 111, 112], [120, 121, 122]], | |
# [[200, 201, 202], [210, 211, 212], [220, 221, 222]]] | |
# | |
require 'pp' | |
n = 3 | |
puts "== case 1 ==" | |
a = Array.new(n, 0) | |
b = Array.new(n){a.clone} | |
c = Array.new(n){b.clone} | |
(0...n).each{|z| | |
(0...n).each{|y| | |
(0...n).each{|x| | |
c[z][y][x] = x + y * 10 + z * 100 | |
} | |
} | |
} | |
pp c | |
puts "== case 2 ==" | |
a = Array.new(n, 0) | |
b = Array.new(n){a.clone} | |
c = Array.new(n){Marshal.load(Marshal.dump(b))} | |
(0...n).each{|z| | |
(0...n).each{|y| | |
(0...n).each{|x| | |
c[z][y][x] = x + y * 10 + z * 100 | |
} | |
} | |
} | |
pp c |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment