【问题标题】:Ruby: How to reference a variable defined outside of a moduleRuby:如何引用在模块外部定义的变量
【发布时间】:2022-07-01 06:15:38
【问题描述】:

如何将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 之类的实例变量,我也会遇到同样的错误

【问题讨论】:

    标签: ruby module scope


    【解决方案1】:

    类似这样的东西(为了举例,我稍微简化了你的类以摆脱依赖关系,但它的结构是相同的):

    class Dummy
      attr_reader :threadpool
      
      def initialize
        processor_pool = "It works"
    
        @threadpool = Module.new do
          define_method :default_executor do
            return processor_pool
          end
          module_function :default_executor
        end
      end
    end
    
    Dummy.new.threadpool.default_executor # => "It works"
    

    【讨论】:

    • 我想你可能误解了这个问题。问题是模块本身找不到对processor_pool变量的引用(上面有注释的那一行)。
    • Ruby 中的方法定义是所谓的“范围门”(其中之一)。这就是为什么在您的变体模块中没有“看到”processor_pool 而在我的一个变体中它确实 - 在您的变体变量中超出范围而在我的变体中它被块捕获并保持可用。跨度>
    猜你喜欢
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 2011-03-30
    相关资源
    最近更新 更多