How to change itself in a block like instance_eval method?

The instance_eval method modifies self in its block, for example:

class D; end d = D.new d.instance_eval do puts self # print something like #<D:0x8a6d9f4>, not 'main'! end 

If we define ourself method (or any other methods (except instance_eval) that accepts the block), when printing self, we will get "main", which is different from instance_eval method.eg:

 [1].each do |e| puts self # print 'main' end 

How can I define a method (which takes a block) like instance_eval? Thanks in advance.

+7
source share
2 answers

You can write a method that takes a proc argument, and then pass this as the proc argument to the_eval instance.

 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 {puts self}

Productivity

 #<Foo:0x100329f00> 
+7
source

It is obvious:

 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 
+3
source

All Articles