About 'dup'

W

Wu Xiaoyi

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?
 
S

Stefano Crocco

|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?

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
 
W

Wu Xiaoyi

Stefano said:
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!!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,122
Latest member
VinayKumarNevatia_
Top