From: GOTO Kentaro Date: 2001-11-15T04:30:40+09:00 Subject: [ruby-talk:25209] Re: Hash clone In message "[ruby-talk:25208] Hash clone" on Thu, 15 Nov 2001 04:18:04 +0900, Niko Schwarz writes: > Hello out there, Hello, > maybe you can help me out: what do I do when I want a copy of a Hash, which > I can modify without altering the previous one? I tried already > Object#clone and Object#dup, but they didnt seem to copy anything... > my hash maps strings to arrays, which again holds integers. > would it help if id restructure it all, so that it maps strings to integers? Array#dup or Hash#dup does `shallow copy'. If you would `deep copy', there are some solutions: * write a method which works as deep copy on the data structure. * use marshal. The latter can be written as follows: def deepcopy(obj) Marshal::load(Marshal::dump(obj)) end h0 = {"foo" => [10,2]} h1 = deepcopy(h0) h1["foo"].push(5) p h1 #=> {"foo" => [10, 2, 5]} p h0 #=> {"foo" => [10, 2]} -- Gotoken