From: Tony Mobily Date: 2006-02-20T19:33:30+09:00 Subject: Re: Class variables and Constants Dear Tony, [OK, I am gonna answer myself] The main difference actually makes a lot of sense. If you change a class constant (which you shouldn't do), then all of the classes which inherited from it will see their constant changed as well. Class variables, on the other hand, are allocated for the class itself. This means that each class (or sub-class) will have its own class variables. Here is some code to clarify the concept. ----------------------------------------------- #!/usr/local/bin/ruby -w class TonyCantCode @@internal=10 def TonyCantCode::something return @@internal end def TonyCantCode::something=(what) @@internal=what end end class TonyReallyCantCode Something=20 end class TonyCantCode2 < TonyCantCode end class TonyReallyCantCode2 < TonyReallyCantCode Something=20 end p TonyCantCode::something p TonyReallyCantCode::Something TonyCantCode::something=30 TonyReallyCantCode::Something=40 p TonyCantCode::something p TonyReallyCantCode::Something p TonyCantCode2::something p TonyReallyCantCode2::Something RESULT: $ ./vars.rb 10 20 ./vars.rb:33: warning: already initialized constant Something 30 40 30 20 <-- !!! --------------------------------------------------- Bye! Merc. On 20/02/2006, at 6:05 PM, Tony Mobily wrote: > Hello people, > > what is the actual difference between class variables and constants? > > If I write: > > ------------------------------------------ > #!/usr/local/bin/ruby -w > > class TonyCantCode > @@internal=10 > > def TonyCantCode::something > return @@internal > end > > def TonyCantCode::something=(what) > @@internal=what > end > > > end > > class TonyReallyCantCode > Something=20 > end > > p TonyCantCode::something > p TonyReallyCantCode::Something > > TonyCantCode::something=30 > TonyReallyCantCode::Something=40 > > p TonyCantCode::something > p TonyReallyCantCode::Something > ------------------------------------------------ > > I get a warning about changing a constant, PLUS I called the method > TonyCantCode::something so that I didn't have to use the brackets > at the end. > > BUT... as far the the scope is concerned, they do seem to be very. > very similar. > As far as I can see: > > * Constants would be referenced mainly from the OUTSIDE of the > class. For example, if TonyReallycantCode::Something was something > very meaningful to the USERS of TonyReallyCantCode. > > * Class variables would be used mainly from WITHIN the class. Yes, > it is possible to create accessors, but they might not be necessary. > > This is what I worked out. Now the question is: is all the above > correct? > > BYE! > > Merc.