From: Chris White Date: 2011-08-15T04:30:00+09:00 Subject: Re: class inheritance and class constants On Aug 14, 2011, at 12:19 PM, Iņaki Baz Castillo wrote: > 2011/8/14 Chris White : >> The listen logic is centralized, and as shown in the UdpServer class, you can override the Server listen and still call its core functionality through `super` > > Hi. My code uses classes rather than instance of classes. Each class > (i.e. UdpServer, TcpServer) has different attributes (listenting IP, > port, transport, and so) and I don't want (due to efficience) to > assign the same value in initialize method for every instance. If they need to stay as classes and not instances, then I recommend the use of a class instance variable: ------------------------------- class Server def self.listen puts "Listening on #@ip" end end class UdpServer < Server @ip = "1.2.3.4" end class TcpServer < Server @ip = "5.6.7.8" end UdpServer.listen TcpServer.listen ------------------------------- What's happening here is that an instance variable is created for both UdpServer and TcpServer. Classes can have instance variables the same as their instances since classes are themselves instances of Class. When listen is called on the class in question, the "self" value is set to the class itself, not Server, and so @ip is the instance variable for the specific server object in question. Regards, Chris White http://www.twitter.com/cwgem