Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a deep copy of an object in Ruby?

I did some searching found some different methods and posts about creating a deep copy operator.

Is there a quick and easy (built-in) way to deep copy objects in Ruby? The fields are not arrays or hashes.

Working in Ruby 1.9.2.

like image 827
B Seven Avatar asked Nov 21 '11 02:11

B Seven


People also ask

How do you deep copy an object in Ruby?

A Trick: Marshalling. "Marshalling" an object is another way of saying "serializing" an object. In other words, turn that object into a character stream that can be written to a file that you can "unmarshal" or "unserialize" later to get the same object. This can be exploited to get a deep copy of any object.

Does clone () make a deep copy?

6.1. Apache Commons Lang has SerializationUtils#clone, which performs a deep copy when all classes in the object graph implement the Serializable interface.

How do you deep copy an object in es6?

If you simply want to deep copy the object to another object, all you will need to do is JSON. stringify the object and parse it using JSON. parse afterward. This will essentially perform deep copying of the object.


2 Answers

Deep copy isn't built into vanilla Ruby, but you can hack it by marshalling and unmarshalling the object:

Marshal.load(Marshal.dump(@object)) 

This isn't perfect though, and won't work for all objects. A more robust method:

class Object   def deep_clone     return @deep_cloning_obj if @deep_cloning     @deep_cloning_obj = clone     @deep_cloning_obj.instance_variables.each do |var|       val = @deep_cloning_obj.instance_variable_get(var)       begin         @deep_cloning = true         val = val.deep_clone       rescue TypeError         next       ensure         @deep_cloning = false       end       @deep_cloning_obj.instance_variable_set(var, val)     end     deep_cloning_obj = @deep_cloning_obj     @deep_cloning_obj = nil     deep_cloning_obj   end end

Source:

http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-list/43424

like image 55
Alex Peattie Avatar answered Oct 07 '22 01:10

Alex Peattie


I've created a native implementation to perform deep clones of ruby objects.

It's approximately 6 to 7 times faster than the Marshal approach.

https://github.com/balmma/ruby-deepclone

Note that this project is not maintained anymore (last commit in 2017, there are reported issues)

like image 24
user2256822 Avatar answered Oct 07 '22 01:10

user2256822