2
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 方法从类外部访问它们吗?

4

1 回答 1

5

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

此外,实例变量不是“默认私有的”(例如 C++ 类的情况),尽管它可能表面上看起来是这样;它们根本无法通过设计在课堂外访问,而不是因为它们是“私有的”(你不能让它们成为“非私有的”。)

于 2009-03-18T01:47:24.113 回答