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?
h
. This might be exactly what is needed by Sayuj for simple String hashes. With more complex objects, this might not be desired anymore. Once could override theHash#dup
method to dup all hashes invalues
recursively. But that would need to be extended for every object type. – Verboten