Discussion: Modifying a hash key
Afficher un message
Vieux 17/09/2007, 10h26   #3
Alex Shulgin
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Modifying a hash key

On Sep 17, 3:42 am, Yukihiro Matsumoto <m...@ruby-lang.org> wrote:
> Hi,
>
> In message "Re: Modifying a hash key"
> on Sun, 16 Sep 2007 17:10:05 +0900, Alex Shulgin <alex.shul...@gmail.com> 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

  Réponse avec citation
 
Page generated in 0,04780 seconds with 9 queries