The following data is available to me in my method:
data from first service call:
date: 2015-04-01 my_array = [{Apple: 3}, {Banana: 2}, {Oranges: 4}]data from second service call:
date: 2015-04-05 my_array = [{Apple: 4}, {Banana: 5}, {Oranges: 1}, {Kiwi: 3}]
At the end of the method, I would like to return an array of hashes which would have data collected from multiple service calls.
The logic should check if the key is already present in the hash, if yes then add the values to the existing key and if not then create a key-value object for that new key. As for this example, my hash after the first service call would look like:
my_final_array = [{Apple: [2015-04-01, 3]}, {Banana: [2015-04-01, 2]}, {Oranges: [2015-04-01, 4]}] However after we get the data from the second service call, I want my final array to be:
my_final_array = [{Apple: [[2015-04-01, 3], [2015-04-05, 4]]}, {Banana: [[2015-04-01, 2], [2015-04-05, 5]]}, {Oranges: [[2015-04-01, 4], [2015-04-05, 1]]}, {Kiwi: [2015-04-05, 3]}] Is there an easy way I can get what I am expecting?
The algorithm which I have is iterating through the data two times i.e. once I create an array to collect the data from all the service calls and then when I iterate over the array to group by keys.
Here is the way I was trying to solve it initially:
dates_array.each do |week_date| my_array = #Collect data returned by service for each week_date. my_array.each do |sample_data| sample_array << [date, sample_data.keys.first, sample_data.values.first] end end sample_hash = sample_array.each_with_object({}) { |data_value, key_name| (key_name[data_value[1]] ||= []) << data_value.values_at(0,2) } #Convert sample_hash to my_final_array for third party input.
{ Kiwi: [[2015-04-05, 3]] }rather than{ Kiwi: [2015-04-05, 3] }.