获得常数的所有者

saw*_*awa 4 ruby constants receiver

使用(n继承)方法,可以通过以下方式实现定义它的接收器/类:

class A
  def foo; end
end

class B < A
end

B.instance_method(:foo).owner # => A
Run Code Online (Sandbox Code Playgroud)

使用(n继承)常量,没有对应的instance_methodmethod方法,所以它并不简单.是否有可能实现定义它的类?

class A
  Foo = true
end

class B < A
end

B.some_way_to_extract_the_owner_of_constant(:Foo) # => A
Run Code Online (Sandbox Code Playgroud)

Aru*_*hit 5

比如,下面的代码:

class A
  Foo = true
end

class B < A
end

B.ancestors.find { |klass| klass.const_defined? :Foo, false }
# => A
Run Code Online (Sandbox Code Playgroud)