From: Florian Frank Date: 2002-12-18T02:43:56+09:00 Subject: Re: Deep copy in Rub? On 2002-12-18 01:53:47 +0900, Jim Freeze wrote: > > My Ruby has it now: > > > > [flori@lambda flori](0)$ irb --prompt xmp > > VERSION > > ==>"1.7.3" > > o = ["foo"] > > ==>["foo"] > > oc = o.deep_clone > > ==>["foo"] > > o[0].equal? oc[0] > > ==>false > I just did a CVS get this morning... OK. The only problem is that I can't commit my patches there. ;) [flori@lambda ruby](0)$ cvs diff object.c Index: object.c =================================================================== RCS file: /src/ruby/object.c,v retrieving revision 1.96 diff -p -u -r1.96 object.c --- object.c 10 Dec 2002 06:23:40 -0000 1.96 +++ object.c 17 Dec 2002 17:34:51 -0000 @@ -152,6 +152,21 @@ rb_obj_clone(obj) } VALUE +rb_obj_deep_clone(obj) + VALUE obj; +{ + VALUE clone; + + if (rb_special_const_p(obj)) { + rb_raise(rb_eTypeError, "can't clone %s", rb_class2name(CLASS_OF(obj))); + } + clone = rb_marshal_load(rb_marshal_dump(obj, Qnil)); + RBASIC(clone)->flags = RBASIC(obj)->flags | FL_TEST(clone, FL_TAINT); + return clone; +} + + +VALUE rb_obj_dup(obj) VALUE obj; { @@ -1332,6 +1347,7 @@ Init_Object() rb_define_method(rb_mKernel, "class", rb_obj_class, 0); rb_define_method(rb_mKernel, "clone", rb_obj_clone, 0); + rb_define_method(rb_mKernel, "deep_clone", rb_obj_deep_clone, 0); rb_define_method(rb_mKernel, "dup", rb_obj_dup, 0); rb_define_method(rb_mKernel, "copy_object", rb_obj_copy_object, 1); The only problem is that marshal doesn't copy the frozen flags for the clone. If it would it could be possible to have "deep_clone" and "deep_dup". -- Most people would rather die than think; in fact, they do so. -- Bertand Russell