How to change self in a block like instance_eval method do?

*爱你&永不变心* 提交于 2019-12-05 21:35:05

问题


instance_eval method change self in its block, eg:

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

If we define a method ourself(or any other methods(other than instance_eval) which takes a block), when print 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.


回答1:


You can write a method that accepts a proc argument, and then pass that as a proc argument to 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 { puts self }

Yields

#<Foo:0x100329f00>



回答2:


It's 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


来源:https://stackoverflow.com/questions/9460736/how-to-change-self-in-a-block-like-instance-eval-method-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!