Round-robin assignment in Ruby
ruby, ruby-on-rails-3
Solution
Array#cycle ( an infinite enumerator) is nice for this:
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}."}
Output
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.
Problem
I have `Enquiry` and `Consellor` models. I want to assign Enquiries to Counsellors in a round robin manner. If there are 3 consellors and 5 Enquiries, then the assignment should be: Enquiry 1 => C1, Enquiry 2 => C2, Enquiry 3 => C3, Enquiry 4 => C1, Enquiry 5 => C2 I can do this by querying DB and optimize by caching, but looking for a better solution.