鉴于以下内容:
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
我缺少什么?
答案 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