1

我知道,它看起来很糟糕,但它工作了一段时间。但是现在用户数量如此之多,以至于系统开始“忘记”它的确切位置(失去与数据库的连接)重写这个嵌套循环的最佳实践是什么?

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 
4

2 回答 2

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

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

于 2012-06-07T13:57:13.737 回答
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
于 2012-06-07T19:41:42.287 回答