Ruby Quicktips Logo

Ruby Quicktips

Random Ruby and Rails tips.
This blog is dedicated to deliver short, interesting and practical tidbits of the Ruby language and Ruby on Rails framework. Read more...

Your submissions are more than welcome!
Nov 26 ’10

Deep clone

Ruby comes with an Object#clone method that lets you copy objects. But this method makes a shallow copy, i.e. a duplicate without copying any referenced objects.

Object#clone:

Produces a shallow copy of obj - the instance variables of obj are copied, but not the objects they reference.

If you need a deep clone of an object - i.e. a copy including referenced objects - the Marshal module is your friend:

deep_cloned = Marshal::load(Marshal.dump(origin))

This tip was submitted by Jaime Iniesta.

3 notes 0 comments

  1. Jaime Iniesta submitted this to rubyquicktips

Comments

You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.

blog comments powered by Disqus