02.13.06
Pitati pametno
Svi koji koristimo open souce (Ruby, Watir…) (i ne samo mi) trebali bi znati kako pitati pametno (tako da dobiješ odgovor).
Chris McMahon je to spomenuo na wtr-general listi.
The only exhaustive testing there is is so much testing that the tester is exhausted. – William C. Hetzel
Svi koji koristimo open souce (Ruby, Watir…) (i ne samo mi) trebali bi znati kako pitati pametno (tako da dobiješ odgovor).
Chris McMahon je to spomenuo na wtr-general listi.
All of us using open source (Ruby, Watir…) (and not only us) should know how to ask questions the smart way (the way that you will get an answer).
Chris McMahon mentioned it at wtr-general mailing list.
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.
class Page
attr_accessor :texts
def initialize(url, texts)
@url, @texts = url, texts
end
end
page_view = Page.new(”app.com/view.aspx”, ["File > View"])
page_view_after_add = page_view.clone
page_view_after_add.texts << “File added.”
puts page_view.inspect
puts page_view_after_add.inspect
Output:
#<Page:0x2820ae0 @url="app.com/view.aspx", @texts=["File > View", "File added."]>
#<Page:0x2820a98 @url="app.com/view.aspx", @texts=["File > View", "File added."]>
But now I new where to look. So I typed "ri Object#clone" and "ri Object#dup" at Command Prompt (and even looked at http://www.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 http://www.rubygarden.org/ruby?Make_A_Deep_Copy_Of_An_Object. 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!
def deep_clone
Marshal::load(Marshal.dump(self))
end
Output:
#<Page:0x4c1dd10 @url="app.com/view.aspx", @texts=["File > View"]>
#<Page:0x4c1dc50 @url="app.com/view.aspx", @texts=["File > View", "File added."]>
I do not understand how it works, and I do not care, as long as it works.