From: "David A. Black" Date: 2010-07-18T19:18:47+09:00 Subject: Re: Infinite Loop in Code -- Logic Error Hi -- On Sun, 18 Jul 2010, James Rasmussen wrote: > David, > > Thank you so much for the help, that makes a lot of sense. Your code was > much more elegant than mine. It was one of those mind-broadening > moments, haha. Good -- I'm pleased. > Concerning my own implementation, I think I figured out the problem as > to why it wasn't working. My code was ugly, but the logic (I thought) > was sound. I was doing some more debugging, trying to figure out why it > would only get to six strings of output, then fail. I found it out. > Here, I make my duplicate for my array: > > rand_spies = spies.dup > rand_spies.sort_by{ rand } > #perform spying operations... > . > . > . > > However, dup copies instance variables over, and it IS a shallow copy, > but if you change an instance variable, based on my debugging, it > changes the original as well. I found this out when (using netbeans) I > put a watch on these variables: > > spies[k].found > rand_spies[l].found > spies[k+1].found > rand_spies[l+1].found > > I found that, even though my rand_spies array was randomized and shallow > copied, it was still making changes to the original array. I found this > when I saw that the rand_spies[l+1].found was being changed when I found > a match in the spies[l].found > > So my question is this: Is there any way to make a shallow copy of an > array of objects, where it passes all the values over, without passing > the reference over? I'm thinking a pass-by-value C++ copy sort of deal. > That's what I need. When you dup an array, you get a new array, but the same objects inside it. So it's not quite right to say that changes to the new array make changes to the original. The two arrays are completely different objects: >> array1 = [1,2,3,4,5] => [1, 2, 3, 4, 5] >> array2 = array1.dup => [1, 2, 3, 4, 5] >> array2.pop => 5 >> array2 => [1, 2, 3, 4] >> array1 => [1, 2, 3, 4, 5] The objects *in* the array, however, are indeed the same. The question you're asking -- a shallow copy where the values are reconstituted, instead of references being passed -- is a contradiction in terms. What makes it "shallow" is the fact that only the array (the container object) is dup'd, while the objects aren't. If you want two arrays of people objects, I would just create two arrays to start with. However, it sounds kind of odd to me, in terms of what you want your program to do (which I might well be misunderstanding). It would mean that even if, say, Clark is "found", the other Clark object would still be able to spy. I'm thinking it might make more sense to reengineer the "found" logic, and the tests for whether or not someone can spy, but keep the basic data structure in place. David -- David A. Black, Senior Developer, Cyrus Innovation Inc. The Ruby training with Black/Brown/McAnally Compleat Philadelphia, PA, October 1-2, 2010 Rubyist http://www.compleatrubyist.com