Iterating over an Array of Hashes

Chad P. wrote in post #996688:

On Thu, May 05, 2011 at 06:21:00AM +0900, Christopher D. wrote:

indicate a desire for the data to change in the original data structure?

No, I’m claiming that the original requester’s statement didn’t
indicate a need to protect against changes resulting from calling
mutating methods on the keys or values of the hashes, only protection
from changes resulting from mutations on the hash.

He didn’t specify “only protection from changes resulting from mutations
on the hash.” He said he didn’t want his actions to change his data
structure, in a very general way.

So you think the folowing statement is a general way, mamby-pamby
statement:

What I want to do…is work on a copy of
each element of b,

In my opinion, you need to ask yourself two questions with regards to
that statement:

  1. What are the elements of b?

  2. Given the op’s code example showing what each element of b looks
    like, does copying such an element require a deep copy or a shallow
    copy?

Taking advantage of a teaching momement, it might have been nice to
point out as an aside that a deep copy can only be accomplished by other
means, but deep copying certainly isn’t necessary for the specific
situation the op posted about.

All,

Apologies, I lost track of the thread.

On Thu, 2011-05-05 at 06:38 +0900, Douglas S. wrote:

So, original poster: what were your intentions? Did you need the only the
hashes in the array preserved, or did you ALSO need the contents of the
hashes in the array preserved? If the former, then clone/dup is fine. If
the latter, then you need some kind of deep copy. The “simplest” deep copy
I can think of is the Marshal#dump/load one.

I just needed the hashes in the array preserved. I’ve done this
with .clone now, and it works like a treat. I now have other problems
over ActiveRecord’s slowness and various other parts of the “correct but
slow” code :slight_smile:

Thanks for your help - this was one area in which I truly had a surprise
when my unit tests failed!

Peter

From the original query:

Is there a way to take a *copy* of the data, rather than a reference
to the data

Data.

He seems, to me, to be talking about data.