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?