我是
Ruby的Nuby.我正在寻找一种方法来获取当前执行行的方法的包含Class对象.这可能没有硬编码类名吗?
# hardcoded example class A def to_s "I am a " + A.to_s # Class "A" is hardcoded here. Is there another way to reference the class A? end end
我认为也许self.class可以工作,但是当类被子类化时它没有给我我想要的东西.
# Following Outputs=> I am a Camel I am a Camel I am a Camel # but I want => I am a Camel I am a Mammal I am a Animal class Animal def to_s "I am a " + self.class.to_s end end class Mammal < Animal def to_s "I am a " + self.class.to_s + " " + super end end class Camel < Mammal def to_s "I am a " + self.class.to_s + " " + super end end puts Camel.new()