3

I need to make a deep copy of an object. The only way I know to make a deep copy of an object is with the following:

Marshal.load(Marshal.dump(my_object))

To my dismay, I found that if some element of the object being deep copied is a proc object then I get an error because proc objects don't have a dump method and can't be deep copied that way.

How do I make a deep copy of an object with procs in them?

ExternalReality
  • 543
  • 4
  • 14

1 Answers1

1

A deep copy in Ruby using clone should do the trick. (Marshalling won't work for some objects... and it makes sense if Procs fall into that category).

clone is a convention that means deep copy, even though deep copies aren't supported in Ruby out of the box. However, an answer on SO to a similar question has a really good, generic, implementation of clone

Community
  • 1
  • 1
RyanWilcox
  • 13,890
  • 1
  • 36
  • 60
  • According to the Object class docs for 1.9.3 clone means shallow copy. I probably don't understand, are you talking about something else? – ExternalReality Dec 16 '11 at 04:36
  • Using `clone` is more of a community convention for deep copy. I agree the docs for `Object#clone` are... not obvious about this. Regardless, you may be able to avoid the whole situation (if you don't like the whole situation) by using `deep_copy` in that SO question I linked to – RyanWilcox Dec 16 '11 at 14:21
  • I don't agree that #clone is a "community convention for deep copy". Neither is #dup. Actually both state in their contract that they are shallow copies. People have certainly undertaken to implement deep copy via #dup and #clone but there is certainly not a community convention that I am aware of. I guess it totally depends on the circumstances what approaches are taken. In my experience deep copying is rarely needed anyway. I have the expression that there is a smell of cargo cult programming around deep copying... – Robert Klemme Sep 18 '12 at 21:14