Cloning into an object

E

Eric Mahurin

Anybody know how to generically copy (shallow like clone) an
object into another object? It would be nice to handle the
case where the objects have a different class, but I would at
least like to know how to do it when the classes are the same.

Here is an example of what I would like to do:

dest = Object.new # or String.new if necessary
source = "hello world"
destid = dest.id

source.clone_into(dest)

dest -> "hello world"
dest.id==destid -> true
dest.class -> String



__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
 
G

George Ogata

Eric Mahurin said:
Anybody know how to generically copy (shallow like clone) an
object into another object? It would be nice to handle the
case where the objects have a different class, but I would at
least like to know how to do it when the classes are the same.

Here is an example of what I would like to do:

dest = Object.new # or String.new if necessary
source = "hello world"
destid = dest.id

source.clone_into(dest)

dest -> "hello world"
dest.id==destid -> true
dest.class -> String

I hear that evil.rb has Object#become, which will do that with some
caveats. Search "Object#become" in the list archives for more info.
 
R

Robert Klemme

George Ogata said:
I hear that evil.rb has Object#become, which will do that with some
caveats. Search "Object#become" in the list archives for more info.

If you just want to copy state you can do without evil magic (although not
working for builtins like String, Array, Fixnum etc.):

class Object
def set_from(o)
o.instance_variables.each do |var|
instance_variable_set( var, o.instance_variable_get( var ) )
end
self
end
end

Kind regards

robert
 
C

Charles Steinman

Eric said:
Anybody know how to generically copy (shallow like clone) an
object into another object? It would be nice to handle the
case where the objects have a different class, but I would at
least like to know how to do it when the classes are the same.

Here is an example of what I would like to do:

dest = Object.new # or String.new if necessary
source = "hello world"
destid = dest.id

source.clone_into(dest)

dest -> "hello world"
dest.id==destid -> true
dest.class -> String

Is the only difference between this and Object#clone that the object_id
is the same as the old object's? Because that's all I can see here, but
I don't understand why that would come in handy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top