-1
如果我在Kernel
模块中使用方法method1
和“全局”method2
的Object1
类。获取区块的呼叫对象
method1
通过将其转换为proc然后调用它来运行该块。
如果我有这样的事情:
obj1 = new Object1
obj1.method1(arg1,arg2){ method2() }
是否有可能在method2
知道obj1
调用块?
如果我在Kernel
模块中使用方法method1
和“全局”method2
的Object1
类。获取区块的呼叫对象
method1
通过将其转换为proc然后调用它来运行该块。
如果我有这样的事情:
obj1 = new Object1
obj1.method1(arg1,arg2){ method2() }
是否有可能在method2
知道obj1
调用块?
假设您希望method2是一个全局方法。您通过传递绑定来获得对调用对象的访问权限。但一个更简单的方法就是给调用者对象传递给它:
例子:
def method2(o)
#puts this.object_id
puts "Inside method2()"
puts "#{o.object_id}"
end
class Object1
def method1
method2(self)
end
end
obj1 = Object1.new
puts obj1.object_id
obj1.method1()
输出:
23644040
Inside method2()
23644040
'method2'并不需要在'Kernel'模块,但需要在每个传递的块中进行访问 – tomatediabolik