0

I'm using ruby, and I want a numeric variable to count the number of instance of my class are called.

I try this ...

class A
  @@count = 0

  def initialize
    @@count += 1
  end
end

class B < A
end

class C < A
end


puts B.new.count #=> 1
puts C.new.count #=> 2

....but obviously the code share the field @@count for classes A, B and C.

Then I try this:

class A
  def self.count
    @count
  end

  def count
    self.class.count
  end
end

class B < A
  @count = 0
end

class C < A
  @count = 0
end

puts B.new.count #=> 0
puts C.new.count #=> 0

It's work, but if i add the filed increment in the subclasses like this:

class B < A
  @count = 0

  def initialize
      @count += 1
  end
end

...ruby return this error:

new 1.rb:15:in initialize': undefined method+' for nil:NilClass (NoMethodError)

Can someone explain me why?

Nifriz
  • 1,033
  • 1
  • 10
  • 21
  • Checkout the self inside initialize method and you will see it refers to instance ^_^ Also you don't have to declare `@count` in A class, because class level accessor methods work with A's `@count` instead of B's or C's instance variable. In other words `@count` in superclass shadows counterparts in the ancestors. TBH, I'd prefer Ruby metaprogramming stuff for the described issue – `ObjectSpace.each_object(B).count` and `ObjectSpace.each_object(C).count` ^_^ Happy hacking! Examples: https://gist.github.com/Tensho/3fb6243dcbaf15df1dbd83ac59583fb6 – Tensho Aug 27 '18 at 20:18
  • Thank you Tensho,Noe I understand. – Nifriz Aug 27 '18 at 20:34
  • @Tensho, stand alone it works, when i use in my program i obtain : "`count': wrong number of arguments (given 0, expected 1+) (ArgumentError) " ... this error is over this line " self.class.count += 1" – Nifriz Aug 28 '18 at 07:59

0 Answers0