You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby:如何在模块实例方法中获取其定义所在的模块?

如何在模块的实例方法中动态获取所在模块?

假设我有如下代码:

module X::Y::Z::M
  def foo
  end
end

如何在foo方法中动态确定它所在的模块X::Y::Z::M?使用self.class无法实现,因为它会返回包含该模块的类。

可以通过方法对象的owner属性来实现,具体代码示例如下:

module X::Y::Z::M
  def foo
    method_owner = method(__method__).owner
    puts method_owner # 输出 X::Y::Z::M
  end
end

class A
  include X::Y::Z::M
end

A.new.foo # 执行后会打印出 X::Y::Z::M

原理说明

  • __method__:返回当前执行方法的名称(符号形式)
  • method(__method__):获取当前方法对应的Method对象
  • owner:Method对象的内置方法,返回该方法最初被定义的模块或类,这里就是目标模块X::Y::Z::M

内容的提问来源于stack exchange,提问作者Keith Bennett

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 07:40:33