Ruby:获取定义当前正在执行的代码的类

Ruby:获取定义当前正在执行的代码的类,ruby,Ruby,如何以编程方式获取定义了当前执行代码的类?由于super(),当控制流通过多个方法定义运行时,我需要查找类: A类 德福 puts(获取当前类) 结束 结束 B类B #=>A 我知道如何获取方法名(使用\uuuuu被调用方\uuuuu,调用方\u位置或\uuu方法);但是类呢?因为ruby中的类也是模块,所以可以通过以下方式实现: 作为以编程方式打印所有类的快速即兴实现,那么: c = C.new method = c.method(:foo) while(method) puts m.o

如何以编程方式获取定义了当前执行代码的类?由于
super()
,当控制流通过多个方法定义运行时,我需要查找类:

A类
德福
puts(获取当前类)
结束
结束
B类C
#=>B
#=>A

我知道如何获取方法名(使用
\uuuuu被调用方\uuuuu
调用方\u位置
\uuu方法
);但是类呢?

因为ruby中的类也是模块,所以可以通过以下方式实现:

作为以编程方式打印所有类的快速即兴实现,那么:

c = C.new
method = c.method(:foo)
while(method)
  puts m.owner
  method = method.super_method
end
# => C
# => B
# => A

(但是,不能保证所有这些方法都会被调用——因为这是在运行时通过
super
!)来确定的)

但是,我甚至无法想象在任何情况下人们会真正需要它。我的意思是,如果你在类
B
中编写一个方法
foo
,那么你就知道你在类
B
中。它就在你屏幕的顶部。是的,我同意。。。我几乎可以肯定的是,我只是在代码中编写
将“Called foo()from class B”
放在代码中,而不是像上面那样“以编程方式”完成!不过,如果您想快速地将调试语句放置在大量位置,这可能很有用。
class A
  def foo
    puts(Module.nesting.first)
  end
end

class B < A
  def foo
    puts(Module.nesting.first)
    super
  end
end

class C < B
  def foo
    puts(Module.nesting.first)
    super
  end
end

C.new.foo
# => C
# => B
# => A
c = C.new
c.method(:foo).owner # => C
c.method(:foo).super_method.owner # => B
c.method(:foo).super_method.super_method.owner # => A
c.method(:foo).super_method.super_method.super_method # => nil
c = C.new
method = c.method(:foo)
while(method)
  puts m.owner
  method = method.super_method
end
# => C
# => B
# => A