From: Eric Mahurin Date: 2005-11-17T08:11:30+09:00 Subject: Re: Proposed RCR: Object#replace On 11/16/05, Austin Ziegler wrote: > class Object > def replace(other) > unless other.class == self.class > raise TypeError, > "cannot convert #{self.class} into #{other.class}" > end > other.instance_variables.each do |name| > instance_variable_set(name, > other.instance_variable_get(name)) > end > end > end > > This is, by the way, exactly what: > > a = {} > b = [] > b.replace a > > does. Yes, I think it should be that restrictive -- exact match only. > This isn't #become, it's #replace. This isn't typecasting, it's > replacing the internals of one object with those of another object OF > THE EXACT SAME KIND. (Granted, singleton objects tend to confuse things, > but this is closer to the behaviour of #dup than of #clone.) The > behaviour for this is relatively well-established by the #replace > implementations on the internal objects Array, Hash, and String. Definitely safer. But, like you said objects with their own meta class do confuse things. But, it still doesn't seem very encapsulated because it is using instance_variable_get on other. If you have an object with instance variables/attributes @x/x/x= and @y/y/y=, here would be a more encapsulated #replace: def replace(other) @x = other.x @y = other.y end other then could be anything as long as it responds to x and y. Of course Array#replace, Hash#replace, etc aren't duck-typed like that, but it would be nice...