在块中获取接收器对象的最简单方法是将对象分配给实例变量。
这个例子更清楚地说明了 lambdas cat_woman 和 robin 如何访问块的接收者对象的属性:
class SuperHeros
attr_accessor :news, :name, :current_task
def initialize(a_name)
@name = a_name
@news = []
end
def batman(task)
puts "Inside the method batman of #{name}: #{task} in progress ..."
@current_task = task
yield
@news << task
end
end
cat_woman = lambda do |extra_task|
puts "cat_woman even #{extra_task} before doing #{@caller_obj.current_task}"
puts "Cat Woman: #{@caller_obj.current_task} - done by #{@caller_obj.name}"
# invoker.news << task
end
robin = lambda do |extra_task|
puts "robin even #{extra_task} before doing #{@caller_obj.current_task}"
puts "Robin: #{@caller_obj.current_task} - done by #{@caller_obj.name}"
end
character_1 = SuperHeros.new('batman_1')
(@caller_obj = character_1).batman("kick Joker's ass") { cat_woman['eats some burger'] }
puts
character_2 = SuperHeros.new('batman_2')
(@caller_obj = character_2).batman("break Bane's bones") { robin['drinks some beer'] }
输出将是:
Inside the method batman of batman_1: kick Joker's ass in progress ...
cat_woman even eats some burger before doing kick Joker's ass
Cat Woman: kick Joker's ass - done by batman_1
Inside the method batman of batman_2: break Bane's bones in progress ...
robin even drinks some beer before doing break Bane's bones
Robin: break Bane's bones - done by batman_2