I have a hash like:
h = {'name' => 'sayuj',
'age' => 22,
'project' => {'project_name' => 'abc',
'duration' => 'prq'}}
I need a dup of this hash, the change should not affect the original hash.
When I try,
d = h.dup # or d = h.clone
d['name'] = 'sayuj1'
d['project']['duration'] = 'xyz'
p d #=> {"name"=>"sayuj1", "project"=>{"duration"=>"xyz", "project_name"=>"abc"}, "age"=>22}
p h #=> {"name"=>"sayuj", "project"=>{"duration"=>"xyz", "project_name"=>"abc"}, "age"=>22}
Here you can see the project['duration']
is changed in the original hash because project
is another hash object.
I want the hash to be duped
or cloned
recursively. How can I achieve this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…