Suppose we are to create an array of hashes in ruby like so:
a = []
h = {:a=”a”}
a << h
h[:a] = “b”
a << h
h[:a] = ‘c”
a << h
What will the array contain? Interestingly, it will contain [{:a=>"c"}, {:a=>"c"}, {:a=>"c"}].
This shows that appending the hash into the array is by reference.
When I had to do something like this I used this very simple work around:
a = []
h = {:a=”a”}
a << Hash[h]
h[:a] = “b”
a << Hash[h]
h[:a] = ‘c”
a << Hash[h]
This causes a new hash to be created and assigned with each append.
Advertisement