Discussion: Modifying a hash key
Afficher un message
Vieux 16/09/2007, 09h07   #1
Alex Shulgin
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Modifying a hash key

Hi,

I'm totally new to Ruby, so please forgive me if I'm asking a trivial
question. :-)

I've wrote this simple program to demonstrate my first major
astonishment with Ruby:

$ cat test-hash.rb
hash={}
key=[1]
hash[key]=1
p hash
key << 2
hash[key]=2
p hash
puts
$ ruby ./test-hash.rb
{[1]=>1}
{[1, 2]=>2, [1, 2]=>1}

$

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.

I know I can use key.clone() to overcome this, but the question is:
what is the reason for hash to store it's keys by reference?

My Ruby and system versions are as follows:

$ ruby --version
ruby 1.8.6 (2007-06-07 patchlevel 36) [i486-linux]
$ uname -a
Linux zrbite 2.6.21-2-686 #1 SMP Wed Jul 11 03:53:02 UTC 2007 i686 GNU/
Linux


Cheers,
Alex

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