From: Kevin Smith Date: 2000-12-30T16:37:47+09:00 Subject: [ruby-talk:8347] How to copy an object? I have a case where I would like to make a deep copy of an object (it happens to be an array, but I don't think that's really important). Both dup and clone make shallow copies, according to the pickaxe book. My goal is to create a copy of my data that I can hand to another class, confident that the other class cannot possibly mess up my precious data. Here's my test code to show what I want: a = 'this is a test' b = 'nope' c = [a, b] d = c p "#{c.inspect}, #{d.inspect}" d[0].chop! p "#{c.inspect}, #{d.inspect}" c[1].chop! p "#{c.inspect}, #{d.inspect}" d[0] = b p "#{c.inspect}, #{d.inspect}" In this case, access through d damages the data, as can be seen via c. When I replace d[0], it also replaces c[0], and when I alter the contents of d[0], it also affects the contents of c[0]. I tried d=c.dup and d=c.clone, but as I expected they didn't change the results. In my real case, the data will not all be strings, so no shortcuts there. Do I have to write my own deep_copy method in every class? Or is there some sneaky shortcut I am missing? Kevin