2012-05-12 94 views
10

我有EnquiryConsellor模型。我想以循環方式將諮詢諮詢分配給諮詢顧問。如果有3個consellors和5次的查詢,則分配應該是:Ruby中的循環分配

查詢1 => C1,查詢2 => C2,查詢3 => C3,查詢4 => C1, 詢問5 => C2

我可以通過查詢數據庫並通過緩存進行優化,但尋找更好的解決方案。

回答

14

陣列#循環(無限枚舉)是很好的這樣的:

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. 
+0

你需要序列數據庫輔導員持久性和每次重新分配它輔導員被創建或銷燬 – DanS