From: Alex Shulgin Date: 2007-09-17T18:30:05+09:00 Subject: Re: Modifying a hash key On Sep 17, 3:42 am, Yukihiro Matsumoto wrote: > Hi, > > In message "Re: Modifying a hash key" > on Sun, 16 Sep 2007 17:10:05 +0900, Alex Shulgin writes: > > |This suggests me that the keys are actually stored in the hash by > |reference, not by value as I would expect from my prior experience > |with other languages. > > Hash stores its values, as its name suggests, by hash values from > keys. So, if you modifies the key, and subsequently the hash value of > the key, it screws up. As a general rule, don't modify the keys, or > if you really need to modify the key for some unknown reason, call > rehash method on the hash. So the real answer to my question (what is the reason for hash to store it's keys by reference?) might be: trading rule of a thumb for speed and memory? If no one is ever going to modify the hash key, there is no reason to copy it... OK, I think I got it. :-) If someone wonder how could I come up with modifying the hash keys: this is my second program in Ruby and was coding a Ruby version of a speech generator example from the Pike & Kernigan's "Practical programming". Here is the code snippet: state={} prefix=[] while $stdin.eof? w=... # read a word state[prefix] << w ... prefix << w # <-- Bang! The hash key is changed... :-) end Cheers, Alex