我有一个例子:
def a
puts "Hello"
end
r = ObjectSpace._id2ref(a.object_id) # r is a reference to a
r == a #=> true
r #=> nil为什么不能用r调用a呢?
发布于 2013-04-19 01:07:45
你不能像那样通过名字来获取方法引用。在您的示例中,当您将a传递给#_id2ref时,它是空的,因为Ruby试图找到一个名为a的本地变量。
a.class => nil
r.class => nil因此,使用r == a是因为r和a都是空的。
但是,您可以使用#method获取对#a的引用
> r = ObjectSpace._id2ref(method(:a).object_id)
=> #<Method: Object#a>
> r == method(:a)
=> true
> r.call
Hello
=> nilhttps://stackoverflow.com/questions/16089075
复制相似问题