From: "David A. Black" Date: 2005-10-06T20:38:01+09:00 Subject: Re: Can Ruby pop like Lisp? Hi -- On Thu, 6 Oct 2005, Kevin Brown wrote: > On Wednesday 05 October 2005 20:51, waterbowl@gmail.com wrote: >> Thx for the replies! >> David A. Black wrote: >>> Actually there's no copying at all in the original example -- it's >>> just a reference to the same object. dup will give you a shallow copy >>> (i.e., a different array, but containing the same objects). > > A different array that contains the same objects is a deep copy. A reference > to the same array is called a shallow copy, because the two 'pointers' point > to the same physical memory. (jee, can you tell I came to Ruby from C++?) I highly recommend coming from Ruby when you use Ruby. It makes everything much more consistent, and ultimately more enjoyable :-) In Ruby you'll find that, given this: x = [1,2,3] y = x what you've got is a copy of the reference, but not a copy of the array. I've never heard the term "shallow copy" applied to a copy of a reference. It's actually an *exact* copy of the reference, and not a copy in any sense of the array object itself. As for dup: the ri description of Object#dup says, in part: Produces a shallow copy of obj---the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. As you can see, the "shallow copy" produced by dup is, indeed, a different array, but containing the same objects: x = ["hi"] y = x.dup x[0].equal?(y[0]) # true That's completely standard usage in Ruby. "Deep copy", on the other hand, means recursing through a container object and copying the contents as well as the container itself: x = ["hi"] y = Marshal.load(Marshal.dump(x)) x[0].equal?(y[0]) # false David -- David A. Black dblack@wobblini.net