Class variable help


I’m trying to figure out why @@people_count isn’t set back to 0 when the second instance of Person is called. The first time it’s called by instance ‘matz’ I get that it increments by 1, but why isn’t it set back to 0 via the line @@people_count=0 when it’s called again?

class Person
  # Set your class variable to 0 on line 3
  @@people_count = 0
  def initialize(name)
    @name = name
    # Increment your class variable on line 8
    @@people_count += 1
  def self.number_of_instances
    # Return your class variable on line 13

matz ="Yukihiro")
dhh ="David")

puts "Number of Person instances: #{Person.number_of_instances}"


because people_count is a class variable, so its shared by all instances.

the behavior you are describing sounds like instance variable behavior.


I understand that I set it as a class variable and that it’s being shared by all instances; what I don’t understand is why the line @@people_count=0 is ignored when the second instance of class Person is called.

What happens to @@people_count after the code goes through dhh =“David”)? It was incremented to 1 and stays at 1 despite the line setting it back to 0?


its not getting set back to zero. When creating the second instance, people_count is simply 1. It has been increased, so the new instance will get the new value (1)

class variable are shared, doesn’t matter if an instance is created later.