public Method

Object.clone

obj.clone  an_object

Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. Copies the frozen and tainted state of obj. See also the discussion under Object#dup.

class Klass
   attr_accessor :str
end
s1 = Klass.new      #=> #<klass:0x401b3a38>
s1.str = "Hello"    #=> "Hello"
s2 = s1.clone       #=> #<Klass:0x401b3998 @str="Hello">
s2.str[1,4] = "i"   #=> "i"
s1.inspect          #=> "#<Klass:0x401b3a38 @str=\"Hi\">"
s2.inspect          #=> "#<Klass:0x401b3998 @str=\"Hi\">"

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.</klass:0x401b3a38>

Source Code

/*
*  call-seq:
*     obj.clone -> an_object
*  
*  Produces a shallow copy of <i>obj</i>---the instance variables of
*  <i>obj</i> are copied, but not the objects they reference. Copies
*  the frozen and tainted state of <i>obj</i>. See also the discussion
*  under <code>Object#dup</code>.
*     
*     class Klass
*        attr_accessor :str
*     end
*     s1 = Klass.new      #=> #<Klass:0x401b3a38>
*     s1.str = "Hello"    #=> "Hello"
*     s2 = s1.clone       #=> #<Klass:0x401b3998 @str="Hello">
*     s2.str[1,4] = "i"   #=> "i"
*     s1.inspect          #=> "#<Klass:0x401b3a38 @str=\"Hi\">"
*     s2.inspect          #=> "#<Klass:0x401b3998 @str=\"Hi\">"
*
*  This method may have class-specific behavior.  If so, that
*  behavior will be documented under the #+initialize_copy+ method of
*  the class.
*/

VALUE
rb_obj_clone(obj)
   VALUE obj;
{
   VALUE clone;

   if (rb_special_const_p(obj)) {
       rb_raise(rb_eTypeError, "can't clone %s", rb_obj_classname(obj));
   }
   clone = rb_obj_alloc(rb_obj_class(obj));
   RBASIC(clone)->klass = rb_singleton_class_clone(obj);
   RBASIC(clone)->flags = (RBASIC(obj)->flags | FL_TEST(clone, FL_TAINT)) & ~(FL_FREEZE|FL_FINALIZE);
   init_copy(clone, obj);
   RBASIC(clone)->flags |= RBASIC(obj)->flags & FL_FREEZE;

   return clone;
}
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.