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