11

我有EnquiryConsellor模型。我想以循环方式将查询分配给辅导员。如果有 3 个 consellors 和 5 个 Enquiries,那么分配应该是:

查询 1 => C1,查询 2 => C2,查询 3 => C3,查询 4 ​​=> C1,查询 5 => C2

我可以通过查询数据库并通过缓存进行优化来做到这一点,但要寻找更好的解决方案。

4

1 回答 1

18

Array#cycle (一个无限的枚举器)很适合这个:

counselors = %w(C1 C2 C3).cycle
enquiries = Array.new(5){|i| "Enquiry #{(i+1).to_s}"}
enquiries.each{|enq| puts "Do something with #{enq} and #{counselors.next}."}

输出

Do something with Enquiry 1 and C1.
Do something with Enquiry 2 and C2.
Do something with Enquiry 3 and C3.
Do something with Enquiry 4 and C1.
Do something with Enquiry 5 and C2.
于 2012-05-12T20:49:27.697 回答