From: Robert Klemme Date: 2005-10-20T23:40:47+09:00 Subject: Re: DbC, const and freeze. Btw: this posting of Ryan was truncated on the news side. Does anybody else have it truncated at their news server, too? 2005/10/20, Ryan Leavengood : > On 10/19/05, John Carter wrote: > > > > For example, look at this hole... > > irb > > irb(main):001:0> a = [[1,2],[3,4]] > > => [[1, 2], [3, 4]] > > irb(main):002:0> a.freeze > > => [[1, 2], [3, 4]] > > irb(main):003:0> a << [9] > > RuntimeError: can't modify frozen array > > from (irb):3:in `<<' > > from (irb):3 > > from :0 > > irb(main):004:0> a[0]<<1 > > => [1, 2, 1] > > irb(main):005:0> a > > => [[1, 2, 1], [3, 4]] > > irb(main):006:0> > > > > Even though "a" was frozen, I still could modify the things "a" contained. > > Fair enough. How about this: Apart from the fact that deep_unfreeze is missing... I still think that the concept of constness doesn't fit Ruby well. There are too many places where you can fiddle with state where you normally (i.e. in other PL's) aren't allowed to. Adding #unfreeze wouldn't help either because it would break the contract of freeze that is used today - IOW code may break. In some cases where modification of an argument must be prevented a delegation based approach may work. I wouldn't go as far as to state that const is overrated but the fact that C++ needed to introduce keyword "mutable" shows that it's not about simply freezing state of an instance. You rather want to freeze observed state... Which brings up an idea.... module Kernel private def const(obj) meth = {} sc = class<> Test = Struct.new(:name, :val) => Test >> obj = Test.new "foo", "bar" => # >> obj.name = "hello" => "hello" >> const obj do ?> obj.name = "new name" >> end RuntimeError: ConstError from (irb):8:in `name=' from (irb):24 from (irb):12:in `const' from (irb):23 from :0 >> p obj.name "hello" => nil >> obj.name="new 2" => "new 2" >> p obj.name "new 2" => nil This can easily be extended to multiple instances... Maybe modification of instance_variable_set does the job, too. > Does anyone else love that name? ;) Can you do #deep_think, too? We then could have #deep_thought?... :-) Kind regards robert