From: 7stud -- Date: 2008-03-07T01:04:13+09:00 Subject: Re: Cloning a module and isolating it from the clone 7stud -- wrote: > > However, I can't figure out a way to make a 'deep copy' where the object > that a reference refers to is also copied. I tried deleting all the > class variables in the cloned module and then adding them back in with > new values--but they still refer to the same objects as the original > module, which is puzzling. > > module A > @@num = 10 > @@arr = [1, 2, 3] > > def A.get_num > @@num > end > > def A.set_num(x) > @@num = x > end > end > > puts A.get_num > > new_meth = %q{ > def B.remove(arr) > arr.each do |name| > remove_class_variable(name.to_sym) > end > end > } > > B = A.clone > B.module_eval(new_meth) > > class_vars = B.class_variables > B.remove(class_vars) > > puts "class variables in B:" > p B.class_variables > > class_vars.each do |name| > B.module_eval("#{name} = 0") > end > > B.set_num("hello") > puts 'After cloning:' > puts A.get_num > puts B.get_num > > A.set_num("goodbye") > puts A.get_num > puts B.get_num > > --output:-- > 10 > class variables in B: > [] > After cloning: > hello > hello > goodbye > goodbye > I see now why that doesn't work. Even though the code changes the class variables in B at the module scope, inside B's methods the class variables still refer to the same objects in A. This demonstrates that: test = %q{ def B.get_my_num @@num #this is the @@num in B at module scope that was erased and replaced end } A.set_num(35.2) B.module_eval(test) puts B.get_num #retrieves the @@num inside get_num which is still a reference to objects in A puts B.get_my_num --output:-- 35.2 0 -- Posted via http://www.ruby-forum.com/.