2012-07-01 69 views
0

在Ruby中,我有一個散列數組和數組。在我的哈希數組中,我想用我的第二個數組中的值替換其中一個鍵值對中的值。什麼是最簡單的方法來完成這一點?Ruby:使用第二個數組的值替換散列數組的鍵值對中的值

實施例(I要替換 「總」 與值從我的第二陣列的值):散列

陣列:

[{"date":"2012-05-27","total":1},{"date":"2012-05-28","total":9}] 

陣列:

[1, 10] 

所需的哈希陣列:

[{"date":"2012-05-27","total":1},{"date":"2012-05-28","total":10}] 

回答

4
array.each_with_index {|e,i| hash_array[i]["total"] = e} 
+0

這似乎並沒有對我的工作。當我運行'array = [1,10]'和'hash_array = [{:date =>「2012-05-27」,:total => 1},{:date =>「2012-05-27」, :total => 9}]'和'array.each_with_index {| e,i | hash_array [i] [「total」] = e}'結果是'[1,10]'而我正在尋找的是[[:date =>「2012-05-27」,:total => 1 },{:date =>「2012-05-27」,:total => 10}]' – diasks2

+0

將total替換爲:total,因爲符號不是字符串。在你的問題中有字符串「total」。 –

+0

嗯,我不知道我做錯了什麼。我仍然得到相同的結果:'array = [1,10]'和'hash_array = [{:date =>「2012-05-27」,:total => 1},{:date =>「2012-05 -27「,:total => 9}]'和'array.each_with_index {| e,i | hash_array [i] [:total] = e}'結果是'[1,10]' – diasks2

1
hashes = [{date: "2012-05-27", total: 1},{date: "2012-05-28", total: 9}] #unquoted keys 
values = [1,10] 

hashes.zip(values){|h,v| h[:total] = v} 
p hashes #=>[{:date=>"2012-05-27", :total=>1}, {:date=>"2012-05-28", :total=>10}]