From: Johann Hibschman Date: 2001-04-29T03:40:18+09:00 Subject: [ruby-talk:14385] Re: Immutable Arrays? In article , Dennis Decker Jensen wrote: > I think it would be better if Hash#[aKeyObject] always duplicated and froze > aKeyObject no matter what the type of aKeyObject should be. That way you > wouldn't have to worry of side-effects. > > Should this become a RCR? Good lord, no. That would make hashes useless for large objects where you don't want the overhead of copying the object. Another problem is that a "copy" of an object is not well defined in general, since it may contain references to other objects, references to itself, and references to the entire system. For strings, this hack works all right. But it's a hack and a blight on the purity of the language. Luckily, I happily admit that you need the occasional impure hack to make a tool usable by actual people, so I'm fine with this. I just don't think it's a good idea to make the hack the rule. On further thought, even freeze doesn't work. rb(main):001:0> a = [1, [2, 3], 4] [1, [2, 3], 4] irb(main):003:0> a.freeze [1, [2, 3], 4] irb(main):004:0> a.hash 23 irb(main):012:0> a[1][0] = 5 5 irb(main):013:0> a.hash 47 So, in general, you can't trust freeze to keep the hash value constant. Hm. That's troubling. Is the only answer "don't do that"? I suppose this is a hard problem. The only "safe" way would be to use a = [1, [2, 3].freeze, 4].freeze which I find a little ugly. Hm. Well, luckily, this doesn't come up all that often. Perhaps hashing on object identity for mutable objects would be a more useful behavior? --Johann