Jano Svitok
8/8/2007 11:51:00 AM
On 8/8/07, Dmitry Bilunov <kmeaw@kmeaw.com> wrote:
> dohzya wrote:
> > Hi,
> >
> > 2007/8/7, Dmitry Bilunov <kmeaw@kmeaw.com>:
> >> # Creates an instance. Guaranties, that a command is safe.
> >> end
> >>
> >>
> >>
> > You want to freeze the object @command, not the class String, don't
> > you ?
> > So you don't need to use an Immutable_String class, just add
> > @command.freeze in your code
>
> It will make impossible changing @command inside instance methods (which
> can be guaranteed to be safe). If there is a way to unfreeze a frozen
> object, then this method could be called externally and one can gain
> write access to an internal instance variable.
Not exactly.
@command is just a pointer to a string, incidentally pointing to same
string as command pointer points to.
So you have three things: 1. the string "safe_command" 2. variable
(=pointer) command, 3. member variable (=pointer) @command.
Now, if you issue @command.freeze, you are not freezing the pointer
@command, but the string it points to, i.e. "safe_command". So if you
do @command.freeze, it is the same as doing "safe_pointer".freeze.
After @command.freeze, you cannot do command.replace - because command
points to a frozen string. However, you can still do command = "abc",
i.e. make command point to another string.
Finally after @command.freeze, you can't do @command.replace either.
But you can do @command = "adsfg" and thus make the pointer point to
another string.
In fact, Hash#[]= dups and freezes String keys, just for the same reason.
Jano