A question.
If I have an object of class “Foo”, I know I can change this object into an
anonymous subclass:
obj = Foo.new
class <<obj
def wibble
# whatever
end
end
obj.wibble
However, suppose I have an existing class hierarchy: Bar is a subclass of
Foo. I want to convert obj from an instance of Foo into an instance of the
subclass Bar.
Is that possible, without creating a whole new Bar object?
(Practical example: I have defined a subclass of the TCPSocket object.
TCPServer#accept returns an object of class TCPSocket. I want to convert
this object into my own subclass)
Thanks,
Brian.
Hi,
However, suppose I have an existing class hierarchy: Bar is a subclass of
Foo. I want to convert obj from an instance of Foo into an instance of the
subclass Bar.
Is that possible, without creating a whole new Bar object?
In general, No.
(Practical example: I have defined a subclass of the TCPSocket object.
TCPServer#accept returns an object of class TCPSocket. I want to convert
this object into my own subclass)
How about extending the socket with your module. See Object#extend.
s = ss.accept
s.extend YourSocketExtensionModule
…
matz.
···
In message “Coercion of variables” on 03/02/02, Brian Candler B.Candler@pobox.com writes:
You can extend that object with features defined in a module to give it
the wanted functionality. Its class won’t change, but adding things to
its singleton class you can get the behavior you want.
···
On Sun, Feb 02, 2003 at 12:38:57AM +0900, Brian Candler wrote:
A question.
If I have an object of class “Foo”, I know I can change this object into an
anonymous subclass:
obj = Foo.new
class <<obj
def wibble
# whatever
end
end
obj.wibble
However, suppose I have an existing class hierarchy: Bar is a subclass of
Foo. I want to convert obj from an instance of Foo into an instance of the
subclass Bar.
Is that possible, without creating a whole new Bar object?
(Practical example: I have defined a subclass of the TCPSocket object.
TCPServer#accept returns an object of class TCPSocket. I want to convert
this object into my own subclass)
–
_ _
__ __ | | ___ _ __ ___ __ _ _ __
'_ \ / | __/ __| '_
_ \ / ` | ’ \
) | (| | |__ \ | | | | | (| | | | |
.__/ _,|_|/| || ||_,|| |_|
Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com
People are going to scream bloody murder about that.
– Seen on linux-kernel
Brian Candler wrote:
(Practical example: I have defined a subclass of the TCPSocket object.
TCPServer#accept returns an object of class TCPSocket. I want to convert
this object into my own subclass)
Two techniques for doing this my be using ‘extend’ to add functionality
to the specific object, or to have your own class delegate to the
TCPSocket object. Both are straightforward.
Dave