1

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 
6
  • Did you write this code, or does it originate from a tutorial somewhere? The inherited method makes use of a class variable Animal.animals rather than an instance variable Animal.new.animals, which you defined in the initializer. Commented Jun 7, 2015 at 22:08
  • Is your intent to maintain an array of instantiated subclasses for the whole Animal class? Commented Jun 7, 2015 at 22:09
  • Yes, I would like to maintain an array of the instantiated subclasses. I want to be able to use metaprogramming and add a subclass to the array each time that one is created. Commented Jun 7, 2015 at 22:22
  • Also, I'm not sure how I can even access this array! thx in advance, i'm kind of confused on this topic Commented Jun 7, 2015 at 22:23
  • add a subclass to the array each time that one is created ... That's a little ambiguous. Do you want to keep an array of all subclass objects that are instantiated, or keep an array merely of the subclasses which are defined to inherit Animal? The former would list 2 dogs and 1 cat if you instantiated them as such, while the latter would always just have 2 elements Dog, Cat regardless of whether either was ever instantiated. Commented Jun 7, 2015 at 22:40

2 Answers 2

2
class Animal class << self attr_reader :animals, :animal_classes end @animals = [] @animal_classes = [] def initialize Animal.animals << self end def self.inherited(subclass) Animal.animal_classes << subclass end end class Dog < Animal end class Cat < Animal end class Armadillo < Animal end dog = Dog.new cat1 = Cat.new cat2 = Cat.new puts "Animals: #{Animal.animals.inspect}" # => Animals: [#<Dog:0x007ffe6d0acaf8>, #<Cat:0x007ffe6d0acaa8>, #<Cat:0x007ffe6d0aca58>] puts "Animal Classes: #{Animal.animal_classes.inspect}" # => Animal Classes: [Dog, Cat, Armadillo] 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that answered how to do it!
1

Use a class variable:

class Animal @@animals = [] def self.inherited(subclass) @@animals << subclass end end 

... if I understand what you're trying to do.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.