Ruby中的循环分配

Pra*_*vin 10 ruby ruby-on-rails-3

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

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

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

ste*_*lag 15

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}."}
Run Code Online (Sandbox Code Playgroud)

产量

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.
Run Code Online (Sandbox Code Playgroud)