>
> Your example doesn't contain nested hashes, while mine does.
Neither did Peter's example and request.
His example was an array with nested hashes -- that is, hashes nested in
an array. It was not hashes nested in hashes, but I do not think that
was what John meant anyway.
>
> That's what I was demonstrating -- it's a shallow copy, not a deep
> one.
Simply using #dup or #clone meets the original request as presented,
and does so for arbitrary Ruby objects in the hashes.
If the Peter needs a deep copy, which Peter didn't ask for (just a copy
of the data in each hash in the array -- not nested hashes -- so that
the originals in the area wouldn't be modified on iteration) its true
that simply using #dup or #clone won't work.
I went back and read the original request. While he did not use the
words "deep copy", the implication of his request seemed pretty clearly
to ask for exactly that, in my estimation. He referred to an array of
hashes; he referred to things being "references" rather than "copies"
(the more formal terminology for those with a pedantic bent would be
"reference copies rather than value copies"); and he referred to the
desire to be able to operate on his data structure in a loop, making
changes, and have those changes lost when the loop exits rather than
saved in the data structure that existed before copying.
The implications of these requirements add up to a request for a way to
get a deep copy.
OTOH, if Peter needs to be able to handle arbitrary Ruby objects in the
hashes, using Marshal.load(Marshal.dump(whatever)) won't work, since
there are objects that can't be dumped.
It meets the need of the example data for the requirements indicated
above. I am not aware of any (relatively trivial) solution to this much
broader problem you're suggesting.
What if the values in the hash are lambdas?
Then yeah, the Marshal dump/load approach doesn't work. It *does* work
for the presented example, though, whereas (given the implications of the
requests in the original questions) your dup-or-clone approach does *not*
work.
The load/dump mechanism meets some other need, but doesn't meet the
original request for hashes with arbitrary data (and is an
extraordinarily convoluted mechanism for meeting the original request
even where it works.)
1. It meets the needs of the presented example data.
2. Is there some less-convoluted approach that works for the more complex
needs you presented?
3. How exactly does this make a dup-or-clone approach work such as what
you presented work?
Its possible to craft a generic deep-copying mechanism, if you need it,
but Marshal.load(Marshal.dump(whatever)) isn't it.
It is not clear to me "generic deep-copying" is exactly what's needed.
···
On Wed, May 04, 2011 at 12:28:18PM +0900, Christopher Dicely wrote:
On Tue, May 3, 2011 at 7:08 PM, John Feminella <johnf@bitsbuilder.com> > wrote:
--
Chad Perrin [ original content licensed OWL: http://owl.apotheon.org ]