在Ruby中传递的块中引用调用对象 [英] Reference the invoking object in the passed block in Ruby
问题描述
是否有任何方法可以在被调用的块内保留被调用的对象.例如,这些块有什么方法可以访问方法batman
或类SuperHeros
Is there any way to get hold of the invoked object inside the block thats being called. For instance, is there any way for the blocks to get access to the scope of the method batman
or the class SuperHeros
class SuperHeros
attr_accessor :news
def initialize
@news = []
end
def batman task
puts "Batman: #{task} - done"
yield "feed cat"
@news << task
end
end
cat_woman = lambda do |task|
puts "Cat Woman: #{task} - done"
# invoker.news << task
end
robin = lambda do |task|
puts "Robin: #{task} - done"
# invoker.news << task
end
characters = SuperHeros.new
characters.batman("kick Joker's ass", &cat_woman)
characters.batman("break Bane's bones", &robin)
推荐答案
您可以使用类似于 Savon中使用宝石:
You can use something similar to Instance eval with delegation pattern, used - for example - in Savon gem:
def batman(task, &block)
@original_self = eval('self', block.binding)
puts "Batman: #{task} - done"
instance_exec('feed cat', &block)
@news << task
end
private
def method_missing(method, *args, &block)
if @original_self
@original_self.send(method, *args, &block)
else
super
end
end
在这种方法中,当您在传递给batman
方法的块中调用方法(使用隐式接收器)时,将在SuperHeros
实例的上下文中调用该方法.如果没有可用的此类方法,则调用(通过method_missing
)转到原始块self
.
In this approach, when you call method (with implicit receiver) inside block passed into batman
method, it's called in the context of SuperHeros
instance. If there is no such method available, the call goes (through method_missing
) to original block self
.
这篇关于在Ruby中传递的块中引用调用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!