Ruby --获取定义类名

doinxwow  于 2023-05-17  发布在  Ruby
关注(0)|答案(1)|浏览(93)

如何获取定义了方法的类?
我发现了如何查找后代和答案:Look up all descendants of a class in Ruby
但这并不一定会让我得到 * 定义类 *(实际上是最后一个定义类)。
我已经找到了如何获取调用类:Ruby Inheritance Get Caller Class Name
但我要的恰恰相反。我想知道如何得到定义类。
我也试过Module.nesting。在这种情况下,我得到了我想要的,但我担心它会不一致,并且在我没有最终控制权的更大的代码库中不可接受。

puts RUBY_VERSION

# Test class vs super.
class Super
    def test_func
      puts "#{self.class}, #{ __method__}"
    end
end

class Child < Super
  def test_func2
     self.test_func
  end
end

Child.new.test_func

我曾希望:
1.8.7
Super,test_func
但得到了:
1.8.7
Child,test_func

bxpogfeg

bxpogfeg1#

你问self.classChild对象,你得到了它。
您需要使用Method#owner来返回定义方法的类或模块。

class Super
  def test_func
    puts "#{method(__method__).owner}, #{ __method__}"
  end
end

class Child < Super
  def test_func2
     self.test_func
  end
end

Child.new.test_func
# will print: Super, test_func

或者只是

Child.new.method(:test_func).owner
#=> Super

Child.instance_method(:test_func).owner
#=> Super

相关问题