Ruby: 如何引用模块外定义的变量
Ruby: How to reference a variable defined outside of a module
如何将processor_pool
传递给模块内部的方法?
class Dummy
def initialize
processor_pool = Concurrent::FixedThreadPool.new(10)
@threadpool = Module.new do
extend Concurrent::Promises::FactoryMethods
def self.default_executor
return processor_pool # this cannot find the processor_pool variable
end
end
end
end
即使我将它设为像 @processor_pool
这样的实例变量,我也会得到同样的错误
类似这样的东西(为了示例,我稍微简化了你的 class 以摆脱依赖关系,但它的结构是相同的):
class Dummy
attr_reader :threadpool
def initialize
processor_pool = "It works"
@threadpool = Module.new do
define_method :default_executor do
return processor_pool # this cannot find the processor_pool variable
end
module_function :default_executor
end
end
end
Dummy.new.threadpool.default_executor # => "It works"
如何将processor_pool
传递给模块内部的方法?
class Dummy
def initialize
processor_pool = Concurrent::FixedThreadPool.new(10)
@threadpool = Module.new do
extend Concurrent::Promises::FactoryMethods
def self.default_executor
return processor_pool # this cannot find the processor_pool variable
end
end
end
end
即使我将它设为像 @processor_pool
类似这样的东西(为了示例,我稍微简化了你的 class 以摆脱依赖关系,但它的结构是相同的):
class Dummy
attr_reader :threadpool
def initialize
processor_pool = "It works"
@threadpool = Module.new do
define_method :default_executor do
return processor_pool # this cannot find the processor_pool variable
end
module_function :default_executor
end
end
end
Dummy.new.threadpool.default_executor # => "It works"