Skip to content

Instantly share code, notes, and snippets.

@jcoglan
Created May 20, 2010 16:10
Show Gist options
  • Select an option

  • Save jcoglan/407741 to your computer and use it in GitHub Desktop.

Select an option

Save jcoglan/407741 to your computer and use it in GitHub Desktop.
def deep_copy(object)
case object
when Array
object.map { |item| deep_copy(item) }
when Hash
object.inject({}) do |hash, (key,value)|
hash[deep_copy(key)] = deep_copy(value)
hash
end
# handle other data structures if need be
else
object.respond_to?(:dup) ? object.dup : object
end
end
@judofyr
Copy link

judofyr commented May 20, 2010

The slower, but simpler approach:

def deep_copy(object)
  Marshal.load(Marshal.dump(object))
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment