2 ruby hash scope class public
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
Run Code Online (Sandbox Code Playgroud)
在我在博客上找到的上面的例子中,我理解TABLE是一个哈希,并且是MySymbol类的成员.我不明白的是如何从String类中公开访问它.我认为类实例变量默认是私有的,你需要使用get/set方法从类外部访问它们吗?
在您的示例中,TABLE是一个常量,而不是实例(或类)变量(即没有前缀的机智)@.
此外,实例变量不是"默认私有"(例如,与C++类一样),尽管它可能表面上看起来那样; 它们在设计之外根本无法访问,不是因为它们是"私有的"(你不能将它们变成"非私人").
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |