Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby dup/clone recursively

Tags:

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?

like image 834
Sayuj Avatar asked Jan 03 '12 10:01

Sayuj


2 Answers

Here's how you make deep copies in Ruby

d = Marshal.load( Marshal.dump(h) ) 
like image 196
Sergio Tulentsev Avatar answered Sep 24 '22 14:09

Sergio Tulentsev


If you are in Rails: Hash.deep_dup

like image 29
fguillen Avatar answered Sep 25 '22 14:09

fguillen