From: Brian Candler Date: 2003-07-07T07:01:59+09:00 Subject: Re: Freezing an arbitary object On Mon, Jul 07, 2003 at 06:53:20AM +0900, Aryeh M. Frierdman wrote: > Thanks for the answers so far but "none" of them actually do what I want. > What I want to do is declare some instance/var/whatever as being invariant Well, you should know what you mean by "whatever" - local variables: cannot be frozen, since they don't belong to an object and are not an object themselves. They can always be reassigned to point to another object. Sorry, that's a Ruby fact of life. - instance variables: are frozen when the object containing them is frozen class Foo attr_accessor :x end a = Foo.new a.x = 99 a.freeze a.x = 100 # TypeError: can't modify frozen object > and any attemt to vary it will result in an error. I am convinced their > has to be some generic way to do this *without* the caller to the "test" > being "aware" that they are asking for it to be froozen. The int example > I gave was only that an example it could of very well been a String, > MyClass, EvilDictator, etc. Taking String as an example: foo = "hello" foo.freeze foo << "x" # Error: object referenced by foo is frozen foo = "bye" # Not error: foo now references a completely different object And it can be done at a distance: def my_test_function(x) x.freeze end foo = "a" my_test_function(foo) foo << "b" # Error: object has been frozen But like I say, local variable "foo" cannot be frozen. I hope that's clear enough... Brian.