Ruby:是否可以在不对类名进行硬编码的情况下确定我的Ruby方法正在执行的类?

我是 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}

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...