Posted in Ruby

Copying Ruby objects: to dup or clone or “=”?

…That is the question!

The Stackoverflow discussion linked to here contains a number of useful bits and bobs with regard to elucidating the difference between the dup and clone methods, and also using “=” to copy a value.

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 are1) 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.

Open source is wide open

Operator “=” does not make a copy, shallow or tainted: it will merely copy the object reference.

A good article on Object states can be found here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s