2013-02-22 53 views
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,如何从动物获得当前的类名没有把infoDog类中。

而且,我得到undefined constant Animal::BREEDS

我失去了什么?

+0

嘛,'hello'是一个类的方法。您还没有创建“Dog”实例,因此没有任何所有者。 – 2013-02-22 22:15:47

+0

杰克我修改了示例代码,使其更有意义,我没有在这个实例中使用 – Ryan 2013-02-22 22:18:30

回答

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 
+0

谢谢Zabba!这正是我想要的:) – Ryan 2013-02-22 22:43:56