如何在rails中仅使用一个for循环同时遍历两个数组

时间:2015-06-30 09:50:14

标签: mysql ruby-on-rails arrays

我想只使用一个for循环同时遍历两个数组。

# For notifications section
@notifications=[]
@challenges=Challenge.where("to_id=? and activity_id=?" ,current_user.id,@activity.id)

@challenges.each do |k|
@match_results=MatchResult.where("challenge_id=? and result_confirmation_status=?" ,@challenges[k].id,1)
end

@challenge=@challenge.reverse
@match_results=@match_results.reverse

然后我想使用" update_at"合并这两个数组。 field表示最新更新的记录应首先保存在数组中。

1 个答案:

答案 0 :(得分:1)

@notifications=[]
@challenges=Challenge.where("to_id=? and activity_id=?" ,current_user.id,@activity.id)
@match_results=[]
@challenges.each do |k|
@match_results=@match_results<<MatchResult.where("challenge_id=? and result_confirmation_status=?" ,k.id,1)
end
@challenges=@challenges.reverse
@match_results=@match_results.reverse

@notifications=(@match_results+@challenges).sort_by(&:updated_at)
@notifications=@notifications.reverse
puts @notifications.inspect