Ruby (Deep) Copy Object
by Željko Filipin
I wanted to make an object. Then copy it. Then change that copy and leave original object intact. But I did not know how to do it. When I do not know how to do something, I always ask wtr-general mailing list. I posted my question. Then I though it would be nice if I explained why I want to copy an object. But it got pretty long, so I put it at my blog.
I got a reply.
Try Object#clone
.
Could it be that easy?! It could be. After all, this is Ruby. But no, it is not that easy. It did not work. Original object was changing with it's duplicate.
Output:
But now I new where to look. So I typed ri Object#clone
and ri Object#dup
at Command Prompt (and even looked at ruby-doc.org/core). It said (at both places, for both Object#clone
and Object#dup
):
Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference.
So, it creates a "shallow" copy. I do not need this. I need a "real" copy.
Google helped me. I searched for "ruby copy object" and found the solution. Secret word is "deep" copy.
I added this to class Page
(and replaced page_view.clone
with page_view.deep_clone
) and got what I needed!
Output:
I do not understand how it works, and I do not care, as long as it works.
tags: code - ruby