I was trying to create an array of hashes, to which i have already found some excellent solutions here:
Creating array of hashes in ruby
However while trying it out on my own, i found some behavior which i didn't understand.
Creating an array of hashes in IRB:
array_hashes = Array.new(7, Hash.new)
Now, on trying to assign key, value pairs to the array:
array_hashes[1]["hello"] = 200
I got the following output in console:
=>[{"hello"=>200}, {"hello"=>200}, {"hello"=>200}, {"hello"=>200}, {"hello"=>200}, {"hello"=>200}, {"hello"=>200}]
The same key , value was repeated across all the array elements, similar results when i tried to assign another key, value to a single array element
array_hashes[3]["world"] = 300
=>[{"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}, {"hello"=>200, "world"=>300}]
Can anyone explain the reason for this, specifically why are hash values repeated across all the array elements even on being assigned to a single element. Thanks!
Ruby Version used: 1.9.3, tried on Windows 7 and OS X Yosemite
Array::new, they even contain the exact example you are asking about.