Ruby中的循环分配

时间:2012-05-12 20:39:19

标签: ruby ruby-on-rails-3

我有EnquiryConsellor个型号。我想以循环方式向辅导员分配咨询。如果有3个consellors和5个查询,那么作业应该是:

  

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

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

1 个答案:

答案 0 :(得分:14)

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.