In Ruby, I have an array of hashes and an array. In my array of hashes, I want to replace the values in one of the key-value pairs with the values from my second array. What is the cleanest way to accomplish this?
Example (I want to replace the value of "total" with the values from my second array):
Array of hashes:
[{"date":"2012-05-27","total":1},{"date":"2012-05-28","total":9}]
Array:
[1, 10]
Desired Array of hashes:
[{"date":"2012-05-27","total":1},{"date":"2012-05-28","total":10}]
array.each_with_index {|e,i| hash_array[i]["total"] = e}
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}]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.