Thursday, February 4, 2010

Difference between .dup and .clone in ruby objects

Being a newbie to Ruby I was confused when I had
to deal with the task of producing an object copy.
I came across this very nice post on a mailing
list which helped me understand the difference.

The crux here is:
Clone copies the entire object as is, including the
any state information the object may contain. While
the duplicate call (.dup) does not copy all of the
state while copying the basic data.

The simplest example which shows the difference is as
follows:

obj1 = []
obj1.freeze
obj2 = obj1.clone
obj3 = obj1.dup
p obj1.frozen?, obj2.frozen?, obj3.frozen?
# => true, true, false

0 comments:

Post a Comment