如何访问超类

时间:2015-06-07 22:02:38

标签: ruby

使用下面的代码,我想打印语句,然后在每次创建新子类时将创建的子类添加到Animal数组中。我想知道如何创建@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

synchronized

2 个答案:

答案 0 :(得分:1)

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]

答案 1 :(得分:0)

使用类变量:

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

...如果我明白你要做什么。