Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 在父模块中访问模块内变量的正确方法_Ruby_Module - Fatal编程技术网

Ruby 在父模块中访问模块内变量的正确方法

Ruby 在父模块中访问模块内变量的正确方法,ruby,module,Ruby,Module,比如说,我有以下情况: module A module B def self.make @correlation_id ||= SecureRandom.uuid end end end 现在,对于外部世界,我只希望他们能够通过模块A访问correlation_id: A.correlation\u id。如何从模块A访问@correlation\u id 我做了以下几件事,效果不错,但有一个我不想要的副作用 module A module B

比如说,我有以下情况:

module A
  module B

    def self.make
      @correlation_id ||= SecureRandom.uuid
    end

  end
end
现在,对于外部世界,我只希望他们能够通过模块A访问correlation_id:

A.correlation\u id
。如何从模块A访问
@correlation\u id

我做了以下几件事,效果不错,但有一个我不想要的副作用

module A
  module B

    def self.make
      @correlation_id ||= SecureRandom.uuid
    end

    private

    def self.correlation_id
      @correlation_id
    end
  end

  def self.correlation_id
    A::B.correlation_id
  end
end
有了它,在我做了
A::B.make
之后,我可以做
A.correlation\u id
,但遗憾的是,我也能做
A::B.correlation\u id
。我如何缓解这个问题

module A
  module B
    def self.make
      @correlation_id ||= SecureRandom.uuid
    end
  end
  def self.correlation_id
    B.instance_variable_get("@correlation_id")
  end
end

为了提高效率,请将
.freeze
放在
之后“@correlation\u id”

这似乎有点过分。我肯定会这么做,但有没有更标准的方法?奇怪的是:)您尝试的一开始就不是标准的(允许
A
访问
A::B
的类实例变量而不允许
A::B
这样做是违反OOP的),所以没有标准的方法。为什么
.freeze
会使这更有效?因为字符串只会在解析时创建并重用。这是最近推出的一项功能。