Creating an Array of Hashes in Ruby
I just made a simple mistake which I figure would be good share with anybody new-ish to Ruby. I wrote the following code to create an array of hashes and fill in some values. Can you guess what the output is?
#!/usr/bin/env ruby
testArray = Array.new(5, Hash.new)
0.upto(4) do |i|
testArray[i][:value] = i
end
0.upto(4) do |i|
puts testArray[i][:value]
end
If you said:
4
4
4
4
4
then you are right. The problem with this code is the Hash.new only creates one hash. And then each element in the array is a reference to that hash. So when any value is changed, all are changed. Instead, moving the hash creation inside the loop fixes everything:
#!/usr/bin/env ruby
testArray = Array.new(5, 0)
0.upto(4) do |i|
testArray[i] = Hash.new
testArray[i][:value] = i
end
0.upto(4) do |i|
puts testArray[i][:value]
end
outputs:
0
1
2
3
4

