gpt4 book ai didi

ruby - 顶层定义的方法在哪里?

转载 作者:数据小太阳 更新时间:2023-10-29 07:30:07 25 4
gpt4 key购买 nike

我正在学习一些元编程,但一直在努力寻找一种方法。假设我有以下类(class):

class MyClass
def self.my_method
end
def your_method
end
end

使用以下代码我可以在对象空间中搜索每个方法:

type = Class
name = /^my_method$/
result = ObjectSpace.each_object(type).select do |o|
o.instance_methods(false).grep(name).size > 0 || o.methods.grep(name).size > 0
end
p result

它发现它显示了以下输出:

[MyClass]

由于搜索器代码还会搜索实例方法,因此在查找 your_method 时会显示相同的输出。

即使我向对象添加单例方法:

mc = MyClass.new
def mc.our_method
end

像这样改变搜索器:

type = Object
name = /^our_method$/
result = ObjectSpace.each_object(type).select do |o|
o.methods.grep(name).size > 0
end
p result

它也找到了它:

[#<MyClass:0x8f86760>]

问题是,如何找到定义在顶级对象中的方法?这个方法:

def hidden
end

另外,定义这样的方法时,当前类是哪个?

最佳答案

Which is the current class when defining a method like this?

我们可以通过检查这个顶级范围内的 self 轻松找出我们所在的对象:

self        #=> main
self.class #=> Object

所以我们不是在一个类中,而是在一个被称为“main”的对象实例中。


How do I find a method defined in the top level object?

这就是它变得有趣的地方。 Ruby 中的顶级作用域对象表现特殊,但发现此处定义的方法所在的位置相对容易:

def foo; :bar; end
method(:foo).owner #=> Object
Object.new.foo #=> NoMethodError: private method `foo' called
Object.new.send(:foo) #=> :bar

所以在顶层定义的方法是对象的(私有(private)*)实例方法。你的“搜索者”找不到它的原因是因为这些方法是私有(private)的,methodsinstance_methods 都不包含私有(private)方法,相反你需要 private_methodsprivate_instance_methods :

Object.instance_methods.include?(:foo)          #=> false
Object.private_instance_methods.include?(:foo) #=> true

* 请注意,Pry(至少 v0.10.1)对此进行了更改,使其 REPL 中的顶层定义方法公开。

关于ruby - 顶层定义的方法在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27242692/

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