我是
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()
解决方法
试试这个
Class.nesting.first
这为您提供了方法的定义类.
class A def example { defining_class: Class.nesting.first,self_class: self.class } end end class B < A end B.new.example # => {:defining_class=>A,:self_class=>B}