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

B Seven picture B Seven · Nov 21, 2011 · Viewed 40.2k times · Source

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.

Answer

Alex Peattie picture Alex Peattie · Nov 21, 2011

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