2008年5月7日 星期三

ruby shoallow copy deep copy

http://zeljkofilipin.com/2006/02/09/ruby-deep-copy-object/
http://phpbb.godfat.org/viewtopic.php?p=1118&sid=db10ef9c975a1b57323311804559ed83
http://saaridev.wordpress.com/2008/01/09/ruby-deep-copy/
http://www.dotnetspider.com/forum/ViewForum.aspx?ForumId=2239



1. # problem
2. a = [[0, 1], [10], 19]
3. b = a.dup
4. b[0][1] = 100 #=> b = [[0, 100], [10], 19] and a = [[0, 100], [10], 19]
b[0] = [3,4] #=> b =[[3,4], [10], 19] and a = [[0, 100], [10], 19]

看起來ruby的 copy 不夠 deep

5.
6. # solution
7. a = [[0, 1], [10], 19]
8. b = Marshal.load(Marshal.dump(a))
9. b[0][1] = 100 #=> b = [[0, 100], [10], 19] and a = [[0, 1], [10], 19]

沒有留言: