获取扩展类的名称

时间:2013-02-22 22:13:27

标签: ruby

鉴于以下内容:

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,如何在不将info类放入Dog类的情况下从动物获取当前的类名。

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

我缺少什么?

1 个答案:

答案 0 :(得分:2)

self.to_s,而不是self.class.to_s。您已在self

中“内部”Animal

要访问常量: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