Can you help me to optimize my code for the following problem:
An array of hashes named expected_tasks has tasks. Each task has a user that has to execute an action and contains fields. The expected_tasks are related to the actual_tasks. We want to execute the expected_task[action] on the actual_task["id]". Therefor want to be able to select the actual_task["id"] where all the fields have the same value.
In the end this means that the expected_tasks[0] matches to the actual_tasks[0] because their fields are exactly the same. When their is a match, we can use actual_task["id"].
This is what the data looks like:
#the fields_to_check is an extraction of the keys of the expected_tasks minus user and action
fields_to_check = [ 'field_to_check_1', 'field_to_check_2' ]
expected_tasks = [{ 'user' => 'user',
'action' => 'action_y',
'field_to_check_1' => 'value_a',
'field_to_check_2' => 'value_a' },{
'user' => 'user',
'action' => 'action_x',
'field_to_check_1' => 'value_b',
'field_to_check_2' => 'value_b'} ]
sparse_actual_subtasks = [{ 'id' => '1' ,
'field_to_check_1' => 'value_b',
'field_to_check_2' => 'value_b' },{
'id' => '2' ,
'field_to_check_1' => 'value_a',
'field_to_check_2' => 'value_a' }]
The piece of code to map the id from actual_task to the right action + user from the expected_task:
expected_tasks.each do |expected_task|
mapped_tasks = []
actual_task = sparse_actual_subtasks.find do |actual_task|
fields_to_check.all? do |field|
expected_task[field] == actual_task[field]
end
end
#map action and user to task with id
actual_task['action'] = expected_task['action']
actual_task['user'] = expected_task['user']
mapped_tasks << actual_task
puts mapped_tasks
end