0

在 Ruby 中,我有一个哈希数组和一个数组。在我的哈希数组中,我想用我的第二个数组中的值替换其中一个键值对中的值。实现此目的最干净的方法是什么?

示例(我想用我的第二个数组中的值替换“total”的值):

哈希数组:

 [{"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

2 回答 2

4
array.each_with_index {|e,i| hash_array[i]["total"] = e}
于 2012-07-01T00:27:54.290 回答
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}]
于 2012-07-01T11:30:18.727 回答