Thursday, April 2, 2009

Ruby - DUP vs CLONE

Both DUP & CLONE can be used to create shallow copy of an object. Both copies the instance variables of obj. But we need to be selective in their usage.

Few difference between these are

1) CLONE copies both FROZEN and TAINTED state of an object, where as DUP only copies TAINTED state of an object.

2) With CLONE you can copy any singleton methods of an object but DUP does not support this.

CLONE is used to duplicate an object, including its internal state, DUP typically uses the class of the descendent object to create the new instance.

I had some bitter experience while using DUP for duplicating an ActiveRecord row, this ended up in losing the original one the same worked fine with CLONE.


A good article on Objects states can be found here


Frozen state:

The object can not be modified any more.

Example
 
a = [ "a", "b", "c" ]
a.freeze
a << "z"

Will return

`<<': can't modify frozen array

1 comment: