【发布时间】: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