From: Robert Klemme Date: 2005-01-26T01:30:50+09:00 Subject: Re: Injecting methods from one class into another. "George Moschovitis" schrieb im Newsbeitrag news:1106667522.708436.185960@z14g2000cwz.googlegroups.com... > > Object methods do not work in vacuum, they usually use instance > > variables to reffer to the object's state, possibly changing it > > (remember encapsulation ;-)?). How would you expect your > > inject_method() deal with it? > > I thought Ruby promotes 'duck typing'. > > I would like to inject specific methods between specific classes. The > destination class has all the instance variables needed to succesfully > execute the method. And what about other methods that are used by a method? I think it's not generally possible to move methods around. But maybe this trick helps: class Object def cast(target_class) copy = case target_class when Class; target_class.allocate when Module; dup else target_class.class.allocate end instance_variables.each do |var| copy.instance_variable_set(var, instance_variable_get(var)) end copy end end Then you can create a tmp copy of an instance with all instance variables copied but a different class. So you can do foo.cast(Bar).bar_method_to_be_called(). Cheers robert