Why do these snippets of code behave differently? I thought they were supposed to do the same thing…
foo = {}
array = []
foo['a'] = "1"
foo['b'] = "2"
array << foo
foo['a'] = "3"
foo['b'] = "4"
array << foo
output => [{"a"=>"3", "b"=>"4"}, {"a"=>"3", "b"=>"4"}]
This is not what I want. Fortunately, I tried using this format, which works:
foo = {}
array = []
foo = {
:a => "1",
:b => "2"
}
array << foo
foo = {
:a => "3",
:b => "4"
}
array << foo
output => [{:a=>"1", :b=>"2"}, {:a=>"3", :b=>"4"}]
What’s going on here?
It’s not
"vs.:— it’s that you’re modifyingfoo(foo[...]=...) in the first example while you’re reassigning the variablefoo(foo=...) in the second. In the first example,foostill refers to the same object (which is also in the array) after you put in the values 3 & 4.For a solution, I recommend the second option (which you can use with
'/"(strings) or:(symbols), no matter), or alternatively you can doarray << foo.cloneto push a copy offooonto the array, so further modifications won’t change it.