我有一個散列數組,我不想修改每個散列。所以我正在迭代我的源數據 - 在這個例子中,只是遍歷數字,我修改每個散列。 但是在迭代器的上下文之外,數組中只有一個元素被修改而不是所有元素,數組的第一個元素被最後一個元素覆蓋。在迭代器中修改散列數組僅修改最後一項
arr = [{ id: 1 }, { id: 2 }, { id: 3 }]
1.upto(3) do |i|
a = arr.detect { |t| t[:id] = i }
a[:content] = 'this is my content'
end
puts arr
輸出
{:id=>3, :content=>"this is my content"}
{:id=>2}
{:id=>3}
期望輸出
{:id=>1, :content=>"this is my content"}
{:id=>2, :content=>"this is my content"}
{:id=>3, :content=>"this is my content"}
Pascal Turbo不會與[Turbo Pascal](https://en.wikipedia.org/wiki/Turbo_Pascal)混淆。 –