Reputation: 1139
Does anyone know how i can iterate over two arrays and match id's from one to the other? I have an Array - @household with a unique id called idhouseholds and would like to tag a field from my @events array to the end of the @household array using the id from @events array.
Upvotes: 0
Views: 370
Reputation: 1703
It seems like what you are looking for is a 'natural join' of two arrays.
In that case, here is something that might work for you:
@household.product(@events).each.map { |x| x if x[0].id == x[1].id }.compact
The code above does a Cartesian product of the two arrays (which gives ALL [household, event] pairs) and then filters out the elements with matching id's.
Of course, if you had an association using the id field, you wouldn't need to do this, it would be handled by the ORM layer.
Upvotes: 4
Reputation: 13593
How about this..
@household.each do |household_elt|
matching_event = @events.select { |event| event.id == household_elt.idhouseholds }.first
#do the tagging with matching_event
end
Upvotes: 0