Jeff Schwab
9/25/2006 6:11:00 PM
Sam Kong wrote:
> Sam Kong wrote:
>> Hi Rubyists,
>>
>> Is there a way to copy an instance method from one class to another?
>>
>> class C1
>> def f
>> p self.class
>> end
>> end
>>
>> class C2
>> end
>>
>> Now I want C2 to have f method so that I can call C2.new.f.
>
> OK. I need to describe what I want.
> Actually this problem is rather imaginary than practical.
> While solving some other problem, this question came into my mind.
> Normally, I would use inheritance or mix-in or maybe delegation.
> This question is "What if...?"
>
> Let's say that there's a class (C1) in a library and I'm building my
> own class hierarchy including C2 (class C2 < SomeOtherClass).
> In such a case, Inheritance or mix-in is not an option.
> However, I want to add a method of C1 into my C2.
> As someone jokingly mentioned, I can copy the source code.
> Let's assume that the method is implemented in C and we don't have theb
> source.
>
> Can we still copy(or reuse) the method?
If the method only exists in a library class, how do you know what it
would do to your class? It sounds like the best way to get the effect
you want might be the same thing you would do in C++ or Java, viz. to
let C2 have a member of type C1, and forward method calls to the member
object according to the "Law" of Demeter.