From: Jason Mayer Date: 2007-01-16T07:18:27+09:00 Subject: Re: Nuby question on Class Variable and Class Instance Variable ------=_Part_97955_4599226.1168899504043 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 1/15/07, Nasir Khan wrote: > > class A > @my_var = 123 > @@my_var = 234 > > def A.cv > @@my_var > end > > def A.cv=(val) > @@my_var = val > end > > class < attr_accessor :my_var > end > end > > Obviously @my_var and @@my_var are two separate entitites, but are similar > in many ways. I have some questions around them, any help is appreciated. > > 1. In terms of the figure in the PickAxe book 2nd Ed (page 381, lucille, > Guitar etc), where would these two variables ( @my_var and @@my_var ) > appear? > 2. If I have a subclass - > class B < A > end > the @@my_var is shared between the parent and child but @my_var is a > separate instance in each of them. Are there any other such differences? > 3. As I have written accessor for @my_var, it most likely becomes a method > in the virtual class A', is there any way to write accessor for @@my_var > using Module's attr_accessor method? > 4. As a general guideline where would I use one or the other? > > > Thanks > Nasir > > Class variables are evil. A smarter man than me said something on the subject of class variables on this list recently. So, hopefully that answers number 4. I'll leave it to the non noobs to answer the others. >You had me at "I generally avoid class variables" :-) > > Here's another one you'll like: > > @@avar = 1 > class A > @@avar = "hello" > end > puts @@avar # => hello > > A.class_eval { puts @@avar } # => hello ------=_Part_97955_4599226.1168899504043--