# http://www.ruby-forum.com/topic/163649
class Array
def shuffle!
n = length
for i in 0...n
r = Kernel.rand(n-i)+i
self[r], self[i] = self[i], self[r]
end
self
end
def shuffle
dup.shuffle!
end
end
def process
@names = Group.find(params[:group]).members.shuffle
# Creates an array of only the name ID
@names_array = []
for name in @names
@names_array << name.id
end
# Group array into groups of two. Add each member of the paired group as the partner_id of the other.
@names_array.in_groups_of(2) {|a|
Member.find(a.first).update_attributes(:partner_id => a.last)
Member.find(a.last).update_attributes(:partner_id => a.first)
}
end
Refactorings
No refactoring yet !
Adam
October 20, 2010, October 20, 2010 02:25, permalink
class Member < ActiveRecord::Base
belongs_to :partner
def self.partner!
transaction do
all.sort_by { rand }.in_groups_of(2) do |(first,last)|
next if first.nil? || last.nil?
first.update_attribute(:partner => last)
last.update_attribute(:partner => first)
end
end
end
end
Group.find(params[:group]).members.partner!
The purpose of this code is to take a group's members, randomize the order, group them in pairs, and store that pair as a partner_id within the database for that member. I'm especially curious about everyone's opinions on the array creation and how I'm putting the partner ID in the database. There's definitely some code smell here.