开发者

Iterating over two arrays at once

Does anyone know how i can iterate over two arrays and match id's from one to the other? I have an Array 开发者_StackOverflow社区- @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.


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜