Re: Cloning into an object
by Robert Klemme other posts by this author
Apr 30 2005 4:01PM messages near this date
Re: Debugger performance
|
Re: arg, metaclass bug found?
"George Ogata" <g_ogata@[...].au> schrieb im Newsbeitrag
news:87zmvfx6u9.fsf@[...]..
> Eric Mahurin <eric_mahurin@[...].com> writes:
>
> > 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.
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
|