2016-05-19 5 views
0

私はハッシュの配列を持っていますが、それぞれのハッシュを変更することはできません。だから、ソースデータを繰り返し処理しています。この例では単純に数値を繰り返し、各ハッシュを変更します。 しかし、イテレータのコンテキスト外では、すべての要素の代わりに配列の1つの要素だけが変更され、配列の最初の要素は最後の要素によってオーバーライドされました。イテレータ内のハッシュの配列を変更すると、最後のアイテムのみが変更されます

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

使用mapまたはeach

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"}] 
関連する問題