I notice Ruby uses reference copy by default. The problem is I need to
keep two variables keep separate copies of the same data.
If I do this:
x = Hash.new
fill a with data
y = x
delete some keys from x
I got those same keys deleted from y ('cos x & y reference the same
data, I believe). How to tell ruby that I want y keep a separate copy
of x’s data, so that if I do anything to x, y is not effected.
y = x.dup may be sufficient for you (it does a shallowcopy).
–
patrick
Thanks, it worked. Now, what are the differences between object#dup
and object#clone. Both doing shallow copy.
Also, when I do this
a = Hash.new
puts(a.id)
Ruby whines no such method existed. The docs mentioned object#id, and
all are descendant of object class. What’s wrong? How can I verify
(other than a handful of puts) if indeed two objects do not share the
same data, but each has own copy?
Ricky, there is equal? method for just this purpose
C:\Documents and Settings\Administrator>ri Object#eql
------------------------------------------------------------ Object#eql?
obj == other => true or false
obj.equal?(other) => true or false
obj.eql?(other) => true or false
Equality---At the +Object+ level, +==+ returns +true+ only if
obj
and other are the same object. Typically, this method is
overridden in descendent classes to provide class-specific
meaning.
Unlike +==+, the +equal?+ method should never be overridden by
subclasses: it is used to determine object identity (that is,
+a.equal?(b)+ iff +a+ is the same object as +b+).
The +eql?+ method returns +true+ if _obj_ and _anObject_ have the
same value. Used by +Hash+ to test members for equality. For
objects of class +Object+, +eql?+ is synonymous with +==+.
Subclasses normally continue this tradition, but there are
exceptions. +Numeric+ types, for example, perform type conversion
across +==+, but not across +eql?+, so:
1 == 1.0 #=> true
1.eql? 1.0 #=> false