2013-02-22 51 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