With the code below, I want to print the statement, then add the subclass created into @animals array every time a new subclass is created. I'd like to know how I can create an instance of Animal and use its variable @animals.
class Animal attr_accessor :animals def initialize @animals = [] end def self.inherited(subclass) puts "a new subclass of #{subclass} was created" Animal.animals << subclass end end class Dog < Animal end class Cat < Animal end dog = Dog.new cat = Cat.new
inheritedmethod makes use of a class variableAnimal.animalsrather than an instance variableAnimal.new.animals, which you defined in the initializer.Animalclass?Animal? The former would list 2 dogs and 1 cat if you instantiated them as such, while the latter would always just have 2 elementsDog, Catregardless of whether either was ever instantiated.