Twice the @, twice as Classy


#1

Why @@people_count does not reset to zero when the class is called again?

https://www.codecademy.com/courses/ruby-beginner-en-MFiQ6/1/4?curriculum_id=5059f8619189a5000201fbcb#

I don't get why @@perople_count is not equal to one at the end of the exercise. If @people_count is set to zero in line 3, shouldn't it be reseted when called the second time -> dhh = Person.new("David")


#2

The @@people_count variable belongs to the class itself, not to instances of the class. It's set once, to the value 0, when the class definition is first read by the interpreter (which happens only once).

The instance does not internally store its own, different version of @@people_count - there's only one "copy" of that variable and it can't be changed by an instance unless it is done within an instance method.

An easy way to show this is to add a line like puts "reading the Person class" directly under @@people_count and seeing what happens. You will be able to see that this is only called when the interpreter initially reads the class, but not when new instances of Person are created.

Hopefully that makes sense!


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.