重写嵌套循环

时间:2012-06-07 13:15:00

标签: ruby architecture

我知道,它看起来很糟糕,但它有一段时间了。但是现在用户数量如此之大以至于系统开始“忘记”它到底在哪里(失去与数据库的连接) 重写这个嵌套循环的最佳做法是什么?

User.all.each_with_index do
 get Subset of criteria to select data
 Subset1.each do
  getSubset2
   Subset2.each do
    getSubset3
     Subset3.each do
      getSubset4
       Subset4.each do
        compute something
         open file A
          create or update a line
         end
        end
       end
     end
   end 
end

编辑: 子集是查询或预定义数组。我正在尝试按照建议将其组合,将brb

User.all.each_with_index do |user|
 Subset1.each do |parameter1|
   Subset2(function(user,parameter1)).each do |object2|
     Subset3.each do |parameter3|
       getSubset4(user, parameter1, object2, parameter3)
         Subset4.each do |data|
          p data
         end
     end
   end
 end
end 

2 个答案:

答案 0 :(得分:1)

subset1 = %w(a b c )
subset2 = %w(d e f g )
subset3 = [1,2,3,4,5]

subset1.product(subset2, subset3) do |data|
  p data
end

这与三重循环具有相同的效果。

答案 1 :(得分:1)

小猪退出了@ steenslag的回答,假设你的用户是

#name, gender, city, profession
Alice, female, Los Angeles, doctor
Bob, male, Los Angeles, lawyer
Carol, female, New York, astronaut
David, male, New York, programmer

而不是遍历所有用户,然后是城市的所有用户,然后是性别的所有用户,打破这些嵌套查询。

#bad
User.each do |u1|
  u1.cities.each do |u2|
    u2.genders.each do |u3|
      u3.professions.each do |u4|
        u4.some_method
      end
    end
  end
end

#better
cities = ["Los Angeles", "New York"]
genders = ["female", "male"]
professions = ["lawyer", "doctor", "astronaut", "programmer"]
criteria = cities.product(genders, professions)

现在,您可以遍历一个收集所有这些数组的叉积的数组(条件)。

criteria.each do |cr|
  city, gender, profession = cr
  u = User.find_by_city_and_gender_and_profession(city, gender, profession)
  u.some_method
end