我是一个ruby newb,并且在访问循环变量的循环内创建的procs有问题。这是一个证明问题的代码文件。
class Route
def initialize options = {}
options.each do |k,v|
self.instance_variable_set("@#{k}", v)
self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")})
self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)})
end
end
end
routes = []
routes << Route.new({ :url=>'/one', :content=>'html1' })
routes << Route.new({ :url=>'/two', :content=>'html2' })
blocks = []
for route in routes
blocks << Proc.new { route.content }
end
puts blocks[0].call #=> 'html2'
puts blocks[1].call #=> 'html2'
如何制作块[0] .call return'html1'和blocks [1] .call return'html2'
答案 0 :(得分:3)
您可以在块内创建Proc,为每个Proc提供不同的上下文:
class Route
def initialize(options = {})
options.each do |k,v|
self.instance_variable_set("@#{k}", v)
self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")})
self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)})
end
end
end
routes = []
routes << Route.new({ :url=>'/one', :content=>'html1' })
routes << Route.new({ :url=>'/two', :content=>'html2' })
blocks = routes.map { |e| Proc.new { e.content } }
puts blocks[0].call #=> 'html1'
puts blocks[1].call #=> 'html2'