From: Robert Klemme Date: 2004-12-14T04:27:19+09:00 Subject: Re: Hash freezes String keys and returns copy "Michael Neumann" schrieb im Newsbeitrag news:41BDDE56.3030305@ntecs.de... > ts wrote: >>>>>>>"M" == Michael Neumann writes: >> >> >> M> okay... but isn't it the same when using a String? >> >> this is made volontary for efficienty : otherwise each time that you >> modify an object, used as a key, ruby will need to re-hash the hash if >> you >> don't want to have strange result like the example that I've given >> >> In reality when you write >> >> a = "test" >> hash[a] = "test" >> >> the key and `a' share the same string, but `a' is marked copy-on-write >> >> M> they behave differently. >> >> Search the archive of [ruby-talk] for this :-) > > Ah, IIRC it has something to do with common usage of strings as keys. Yes, it's a special optimization for string keys. You can get your original out if you freeze it before putting it into the hash. :-) In fact, that might be a performance optimization if you put *a lot* string keys into the hash. Because copying an instance is relatively expensive this pattern was not adopted generally, i.e. you have to take care of Array and other keys yourself. Note also, that you need to rehash if you change your array instance after using it as Hash key. Kind regards robert