dblack / candle.superlink.net wrote:
> Hi --
> 
> On Fri, 15 Nov 2002, Gennady F. Bystritsky wrote:
> 
> 
>>I thought that I knew Ruby pretty well until I came accross this thread
>>about "class instance variables". It always haunted me why it does not work
>>when I do
>>
>>   @var = value
>>
>>outside any method definition, meaning initialization of an instance
>>variable. Now I see why. Hence the question: is there any practical use for
>>"class instance variables"? If so, would anybody post an example?
> 
> 
> 
> One potentially good thing, though I can't claim to have any dazzling
> examples, is that a class's instance variables can be used as true
> class-scoped variables, as opposed to class variables which are sort
> of tree-scoped.

A slightly more elaborate example, showing how it can be useful to have 
per-class rather than per-class-tree variables:


class A
   class << self
     def new(*args)
       @count ||= 0
       @count += 1
       super
     end

     attr_reader :count
   end
end

class B < A
end

10.times { A.new }
20.times { B.new }

p A.count # ==> 10
p B.count # ==> 20

Note that count is the number of *direct* instances of the class (A or 
B) which have been created, not the number that currently exist.