【问题标题】:Why is this publicly accessible in my example: "MySymbol::TABLE"为什么在我的示例中可以公开访问:“MySymbol::TABLE”
【发布时间】:2010-10-13 23:45:42
【问题描述】:
class MySymbol
  TABLE={}
  def initialize(str) @str = str end
  def to_s() @str end
  def ==(other)
    self.object_id == other.object_id
  end
end

class String
  def my_intern
    table = MySymbol::TABLE
    unless table.has_key?(self)
      table[self] = MySymbol.new(self)
    end
    table[self]
  end
end

"foo".my_intern

在我在博客上找到的上述示例中,我知道 TABLE 是一个哈希并且是 MySymbol 类的成员。我不明白的是如何从 String 类内部公开访问它。我认为类实例变量默认是私有的,您需要使用 get/set 方法从类外部访问它们吗?

【问题讨论】:

    标签: ruby class hash scope public


    【解决方案1】:

    在您的示例中,TABLE 是一个常量,而不是一个实例(或类)变量(即不以 @ 为前缀。)

    此外,实例变量不是“默认私有的”(例如,与 C++ 类一样),尽管表面上看起来是这样;它们根本无法在类之外访问设计,并不是因为它们是“私有的”(你不能将它们设为“非私有的”。)

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 2020-11-03
      • 2014-09-27
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 2011-02-06
      • 2020-09-17
      • 1970-01-01
      相关资源
      最近更新 更多