ruby-1.9.2-p180 :154 > a = []
=> []
ruby-1.9.2-p180 :154 > h = {:test => "test"}
=> {:test=>"test"}
ruby-1.9.2-p180 :155 > a << h
=> [{:test=>"test"}]
ruby-1.9.2-p180 :156 > h.clear
=> {}
ruby-1.9.2-p180 :157 > a
=> [{}]
I’m very confused, especially since I can change the elements of the hash without it affecting the array. But when I clear the hash the array is updated and cleared of its hash contents. Can someone explain?
When you do
a << h, you are really passing the reference of h to a. So when you update h, a also see’s those changes because it contains a reference rather than a copy of that value.In order for it not to change in a, you must pass a cloned value of h into a.
An example would be: