2016-05-19 29 views
0

我有一個散列數組,我不想修改每個散列。所以我正在迭代我的源數據 - 在這個例子中,只是遍歷數字,我修改每個散列。 但是在迭代器的上下文之外,數組中只有一個元素被修改而不是所有元素,數組的第一個元素被最後一個元素覆蓋。在迭代器中修改散列數組僅修改最後一項

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"} 
+0

Pascal Turbo不會與[Turbo Pascal](https://en.wikipedia.org/wiki/Turbo_Pascal)混淆。 –

回答

2

使用mapeach

arr = [{ id: 1 }, { id: 2 }, { id: 3 }] 
arr.map { |e| e.merge(content: 'this is my content')} 
=> [{:id=>1, :content=>"this is my content"}, 
    {:id=>2, :content=>"this is my content"}, 
    {:id=>3, :content=>"this is my content"}] 

或者你可以在你的代碼=更換==

a = arr.detect { |t| t[:id] == i } 

== - 平等,= - 分配

+1

@PascalTurbo在我的答案我說問題。你使用賦值而不是平等。 – Ilya

0

如果要修改的arr的元素,你可以寫:

arr = [{ id: 1 }, { id: 2 }, { id: 3 }] 

arr.map { |h| h.tap { |g| g[:content] = "this is my content" } } 
    # => [{:id=>1, :content=>"this is my content"}, 
    #  {:id=>2, :content=>"this is my content"}, 
    #  {:id=>3, :content=>"this is my content"}]