Jesús Gabriel y Galán
10/17/2008 8:21:00 AM
On Fri, Oct 17, 2008 at 9:41 AM, Tommy Nordgren
<tommy.nordgren@comhem.se> wrote:
>
> On Oct 17, 2008, at 7:19 AM, Mike Gold wrote:
>
>> Tommy Nordgren wrote:
>>>
>>> def Bob.count
>>> return @@count
>>> end
>>
>> I avoid @@. Why should metaclasses have a different syntax? @@ also
>> has different scoping rules which I find vexing. Be consistent, I say.
>>
> An instance counter have to be assosiated with the class itself, and
> not
> an instance. How else can it count the total number of allocated instances?
> You plainly did not read the original posters message.
A Class is also an object that can have its own instance variables,
which are different
from the instance variables of instances of that class. People usually
discourage the
use of class variables (@@x) because they have "weird" semantics when it comes
to inheritance, and using class instance variables is usually better
and covers most
cases:
irb(main):001:0> class B
irb(main):002:1> @count = 0
irb(main):003:1> class << self
irb(main):004:2> attr_accessor :count
irb(main):005:2> end
irb(main):006:1> attr_accessor :count
irb(main):007:1> def initialize
irb(main):008:2> B.count += 1
irb(main):009:2> end
irb(main):010:1> end
=> nil
irb(main):011:0>
irb(main):012:0*
irb(main):013:0* B.count
=> 0
irb(main):014:0> b = B.new
=> #<B:0xb7b77188>
irb(main):015:0> B.count
=> 1
irb(main):016:0> b.count
=> nil
irb(main):017:0> b.count = 55
=> 55
irb(main):018:0> b.count
=> 55
irb(main):019:0> B.count
=> 1
So, B.count and b.count are different things. B.count accesses an
instance variable of B, while b.count accesses instance variables of B
instances.
Jesus.