Ruby dup/clone recursively

Sayuj picture Sayuj · Jan 3, 2012 · Viewed 9.8k times · Source

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?

Answer

Sergio Tulentsev picture Sergio Tulentsev · Jan 3, 2012

Here's how you make deep copies in Ruby

d = Marshal.load( Marshal.dump(h) )