When do you use a class method (i.e. self.number_of_instances)



When do you use a class method (i.e. self.number_of_instances).


Replace this line with your code.

`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
return @@people_count

matz = Person.new("Yukihiro")
dhh = Person.new("David")

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


In this example the class variable in incremented each time a new object is instantiated. The @@people_count variable keeps track of the number of instances of the class.

This method is internal to the class, and not callable by an instance. That is why it must be called on the actual class, Person.


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