got the answer from ruby list:

dup is a "shallow" copy. For a Hash, you'll get a new Hash but with the
keys and values pointing to the same objects.

>> h1 = {1=>"one", 2=>"two"}
=> {1=>"one", 2=>"two"}
>> h2 = h1.dup
=> {1=>"one", 2=>"two"}
>> h1.object_id
=> -605621648
>> h2.object_id
=> -605633988           #<< the hashes are different objects
>> h1[1].object_id
=> -605621708
>> h2[1].object_id
=> -605621708           #<< the values are the same object
>>

If you want a deep copy, you have to do it yourself.

Similarly, if you freeze a Hash, you are just freezing the Hash itself,
not all the objects it points to.

>> h1
=> {1=>"one", 2=>"two"}
>> h1.freeze
=> {1=>"one", 2=>"two"}
>> h1[2] << "xxx"
=> "twoxxx"
>> h1
=> {1=>"one", 2=>"twoxxx"}

If you want a "deep freeze" then you'll have to do it yourself.

Your test code looks rather more convoluted than it needs to be, so you
should be able to boil it down to a two or three line case which shows
you what's happening.

** Changed in: ruby1.8 (Ubuntu)
       Status: New => Invalid

-- 
ruby dup unexpected behaviour
https://bugs.launchpad.net/bugs/384265
You received this bug notification because you are a member of Ubuntu
Bugs, which is subscribed to Ubuntu.

-- 
ubuntu-bugs mailing list
ubuntu-bugs@lists.ubuntu.com
https://lists.ubuntu.com/mailman/listinfo/ubuntu-bugs

Reply via email to