Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round-robin assignment in Ruby

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.

like image 718
Pravin Avatar asked May 12 '12 20:05

Pravin


1 Answers

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.
like image 162
steenslag Avatar answered Oct 13 '22 18:10

steenslag