From: Florian Gross Date: 2004-12-08T04:57:32+09:00 Subject: Re: Freezing Variable Assignment Nicholas Van Weerdenburg wrote: > Is there a feature to freeze variable assignment? > > e.g. > a="hello" > a.assignfreeze > a="goodbye" # ===> generates exception > > Or, in a related vein, a type freeze, so that only similar objects can be added. The proposed Syntax confuses the object a variable is referring to with the variable itself. It would likely be assign_freeze :var instead. But I don't think this is general enough to include it directly in Ruby. Let me suggest an idea for a revised request instead: Request a way of specifying a callback for local variable assignment. trace_var already can be used for doing that with global variables. It would be a generalization to also allow this with local ones. The interface would be this: trace_var(:string) do |arg| raise(TypeError, "Can't assign #{arg.inspect} to variable 'string'," + " because it is not a String.") unless arg.is_a?(String) end Using that you could implement assign_freeze() by yourself. But please make sure to think about performance issues. It might be a good idea to implement it and benchmark it and send the patch with statistics to ruby-core. Note that slowdown that is only caused by *using* the new feature (e. g. does not make old code slower) is not much of an issue. Sorry if this sounds like a lot of work, but I think that if you do it like that it would be a very nice feature that would be generally useful to the community without having too much of a downside. It would allow for very powerful meta programming.