About 'dup'

Hello,

mainarray=Hash.new(0)
subarray=Hash.new(0)

thirdarray={
‘a’ => ‘0’,
‘b’ => ‘0’,
‘c’ => ‘0’,
}

subarray[‘first’]=thirdarray.dup
subarray[‘second’]=thirdarray.dup

mainarray[‘x’]=subarray.dup
mainarray[‘y’]=subarray.dup

mainarray[‘x’][‘first’][‘c’]=56
mainarray[‘y’][‘first’][‘c’]=73
p mainarray

the result is:
{“x”=>{“second”=>{“a”=>“0”, “b”=>“0”, “c”=>“0”}, “first”=>{“a”=>“0”,
“b”=>“0”, “c”=>73}},
“y”=>{“second”=>{“a”=>“0”, “b”=>“0”, “c”=>“0”}, “first”=>{“a”=>“0”,
“b”=>“0”, “c”=>73}}}

Why did the mainarray[‘x’][‘first’][‘c’] become 73,too?
dup does not work if I use it twice?

On Friday 12 June 2009, Wu Xiaoyi wrote:

|
|
|the result is:
|{“x”=>{“second”=>{“a”=>“0”, “b”=>“0”, “c”=>“0”}, “first”=>{“a”=>“0”,
|“b”=>“0”, “c”=>73}},
| “y”=>{“second”=>{“a”=>“0”, “b”=>“0”, “c”=>“0”}, “first”=>{“a”=>“0”,
|“b”=>“0”, “c”=>73}}}
|
|Why did the mainarray[‘x’][‘first’][‘c’] become 73,too?
|dup does not work if I use it twice?

The problem is that dup only does a shallow copy of the object. In your
case,
this means it creates a new hash but fills it with the same contents of
the
original one. This means that mainarray[‘x’][‘first’] contains the same
object
as mainarray[‘y’][‘first’] (you can see this by checking the object_id
of the
two). If you want the hashes in mainarray[‘x’] and mainarray[‘y’] to
have
different contents, you need to do a deep copy of subarray. The simpler
way to
do this is to use Marshal.dup and Marshal.load:

mainarray[‘x’] = Marshal.load(Marshal.dump(subarray))
mainarray[‘y’] = Marshal.load(Marshal.dump(subarray))

Of course, this will fail if subarray contains an object which can’t be
marshalled (see the documentation for the Marshal module to see which
they
are). In this case you’ll need to define a more specific method to do
this.

I hope this helps

Stefano

Stefano C. wrote:

On Friday 12 June 2009, Wu Xiaoyi wrote:
I hope this helps
Stefano

Hello,Stefano:
It really worked!Thank you very much!!
It’s very kind of you to offer to help me.I really appreciate you!!