A
Alex Shulgin
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
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