Method: Object#dup

Defined in:
object.c

#dupObject

Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj.

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.

on dup vs clone

In general, clone and dup may have different semantics in descendant classes. While clone is used to duplicate an object, including its internal state, dup typically uses the class of the descendant object to create the new instance.

When using #dup, any modules that the object has been extended with will not be copied.

class Klass

attr_accessor :str

end

module Foo

def foo; 'foo'; end

end

s1 = Klass.new #=> #<Klass:0x401b3a38> s1.extend(Foo) #=> #<Klass:0x401b3a38> s1.foo #=> “foo”

s2 = s1.clone #=> #<Klass:0x401b3a38> s2.foo #=> “foo”

s3 = s1.dup #=> #<Klass:0x401b3a38> s3.foo #=> NoMethodError: undefined method ‘foo’ for #<Klass:0x401b3a38>

Returns:



390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'object.c', line 390

VALUE
rb_obj_dup(VALUE obj)
{
    VALUE dup;

    if (rb_special_const_p(obj)) {
        rb_raise(rb_eTypeError, "can't dup %s", rb_obj_classname(obj));
    }
    dup = rb_obj_alloc(rb_obj_class(obj));
    init_copy(dup, obj);
    rb_funcall(dup, id_init_dup, 1, obj);

    return dup;
}