From: Chris White Date: 2011-08-15T04:55:46+09:00 Subject: Re: class inheritance and class constants > Yes, I also us that commonly. However I didn't know that class > instance variables can be defined out of a method. I expected: > > class TcpServer < Server > def self.init_variables > @ip="5.6.7.8" > end > end > > Good to know that it's not needed :) Yup, and the reason why it works is because class definitions are expressions, where the last expression in the class body is the return of the expression. Since in most cases it's a method definition, the result is generally nil. So what happens is: > class TcpServer < Server > def self.init_variables Notice we have to use self here so it works when calling TcpServer.init_variables. This is because we're at the class declaration stage, so self is set to TcpServer. This binds the method to the specific TcpServer class instead of the instances of the class. So @ip outside of a method declaration is the same principal, as when instance variables are created and accessed, they're bound to the value of self (You can see this at the bytecode / c level here if you want http://blog.rubychest.net/2011/08/know-they-self-instance-variables.html ). Regards, Chris White http://www.twitter.com/cwgem