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
In the example above, which I found on a blog, I understand that TABLE is a hash and is a member of the MySymbol class. What I don’t understand is how it can be accessed publicly from inside the String class. I thought class instance variables are private by default and you need to use get/set methods to access them from outside the class?
In your example,
TABLEis a constant, not an instance (or class) variable (i.e. not prefixed wit@.)Also, instance variables are not ‘private by default’ (e.g. as is the case with C++ classes), although it may superficially look that way; they are simply not accessible outside the class by design, not because they are ‘private’ (you cannot make them ‘non-private’.)