ids_to_limit = []
# collect all the record ids so we don't have to run through every API record
data.each do |record|
ids_to_limit << record_ids.map{|field| record[field]}.join("^")
end
# filter API records whose ID is in the list of source data IDs
api_data = api_data.select{|api_record| ids_to_limit.include? api_record['external_ids'][0]['external_id']}
Something like: