Hi:
I have a class that contains a class (possibly a list of classes).
The container class can also be contained by an other class.
Essentially, the classes are just used as fancy structs to
collect data in.
The problem is, I want to copy objects and have unique instances
of these objects. I can do this by modifying #dup in the parent class,
but I would like it to be more automatic. Maybe I can make this
more clear with an example:
Here is a normal case:
class Box
attr_accessor :item
def initialize
@item = "item"
end
end
class Package
def initialize
@b = Box.new
end
def change_item
@b.item = "changed"
end
def to_s
@b.item
end
end
c1 = Package.new
c2 = c1.dup
puts "c1:#{c1}"
puts "c2:#{c2}"
c1.change_item
puts "c1:#{c1}"
puts "c2:#{c2}"
--> Output
c1:item
c2:item
c1:changed
c2:changed
This is not what I wanted. I want
c2 to have its own copy of the data.
I can get this by I modifying Package#clone thusly:
class Package
def clone ## called by #dup
copy = super
@b = @b.dup
copy
end
end
--> Output
c1:item
c2:item
c1:changed
c2:item
Thanks works fine, but it puts the responsibility
on the container class to modify #clone.
And if I have alot of different classes/object,
it is a problem waiting to happen.
Is there a way to modify the Box class
to make unique copies automatically?
Or, is there a different way to look at the problem
and collect data differently?
Thanks
=========================================================
Jim Freeze
jim / freeze.org
---------------------------------------------------------
No comment at this time.
http://www.freeze.org
=========================================================