0

鉴于以下情况:

class Animal
  def self.info
    "This is the class '#{self.class.to_s}', and the available breeds are #{BREEDS.to_s}"
  end
end

class Dog < Animal
  BREEDS = %w(x y z)
end

当我打电话时:

Dog.info
=> This is the class 'Class'

我期待Dog而不是Class,我如何从 Animal 获取当前的类名而不放入info类中Dog

另外,我得到undefined constant Animal::BREEDS

我错过了什么?

4

1 回答 1

2

self.to_s,不是self.class.to_s。你已经在“里面”selfAnimal

要访问常量: self::BREEDS

所以:

class Animal
  def self.info
    "This is the class '#{self.to_s}', and the available breeds are #{self::BREEDS.to_s}"
  end
end
于 2013-02-22T22:25:43.847 回答