0

I have this code:

class Person
  @@instance_count = 0

  def initialize name
    @name = name
    @@instance_count += 1
  end
  def self.instance_count
    p "Instances created - #{@@instance_count}"
  end
end

person_1 = Person.new "first_name"
person_2 = Person.new "second_name"
person_3 = Person.new "third_name"

Person.instance_count

which outputs "Instances created - 3".

I do not understand why += in initialize increments @@instance_count and not resets it to 0 every time a new instance variable is created. What is happening when @@instance_count is not reset to 0 every time a new instance is created?

1
  • Because there's only one instance of that variable. No new ones are created. Probably you confuse class variables (@@var) with instance variables (@var) Commented May 3, 2014 at 19:27

1 Answer 1

3

A variable whose name begins with '@' is an instance variable of self. An instance variable belongs to the object itself.

@foobar

A class variable is shared by all instances of a class and begins with '@@'.

@@foobar

Here is the source: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Variables_and_Constants#Instance_Variables

EDIT

# This is a class
class Person
  @@instance_count = 0

  # This is the class constructor
  def initialize name
    @name = name
    @@instance_count += 1
  end

  def self.instance_count
    @@instance_count
  end
end

# This is an instance of Person
toto = Person.new "Toto"
# This is another instance of Person
you  = Person.new "Trakaitis"

p Person.instance_count # 2

@@instance_count is a class variable it is attached to the class itself, not to its instantiations. it's part of the class definition, such as the methods. Let's say it is created and set to 0 once ruby has parsed your class code.

When you create a new instance of this class using new (toto = Person.new "Toto"), the class constructor will be called. So @name will be created as a local variable to the new instance, and @@instance_count, that has been set to 0 previously, will be recognized and incremented by 1.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.