如何在像instance_eval方法的块中更改self?
instance_eval方法在其块中更改self,例如:
class D; end d = D.new d.instance_eval do puts self # print something like #, not 'main'! end
如果我们定义一个方法selfelf(或任何其他方法(除了instance_eval)接受一个块),当print self时,我们将获得’main’,这与instance_eval方法不同.eg:
[1].each do |e| puts self # print 'main' end
如何定义像instance_eval这样的方法(采用块)? 提前致谢。
您可以编写一个接受proc参数的方法,然后将其作为proc参数传递给instance_eval。
class Foo def bar(&b) # Do something here first. instance_eval &b # Do something else here afterward, call it again, etc. end end
Foo.new.bar {置身}
产量
#
很明显:
class Object def your_method(*args, &block) instance_eval &block end end receiver = Object.new receiver.your_method do puts self #=> it will print the self of receiver end