gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 16:16:12 25 4
gpt4 key购买 nike

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

class A
def foo
puts(get_current_class)
end
end

class B < A
def foo
puts(get_current_class)
super
end
end

class C < B
def foo
puts(get_current_class)
super
end
end

C.new.foo
# => C
# => B
# => A

我知道如何获取方法名称(使用__callee__caller_locations__method__);但是类(class)呢?

最佳答案

由于 ruby​​ 中的类也是模块,这可以通过 Module#nesting 来实现:

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

或者,如果目标是构建对象的祖先链可以调用哪些方法的列表,那么您可以使用Method#owner。和 Method#super_method (可用 since ruby version 2.2.0 ):

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

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

关于Ruby:获取定义当前执行代码的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44230926/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com