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.
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.
6.1. Apache Commons Lang has SerializationUtils#clone, which performs a deep copy when all classes in the object graph implement the Serializable interface.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With