2722012beb9afcad75df5c9f2229fd8c

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.

# 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 !

A8d3f35baafdaea851914b17dae9e1fc

Adam

October 20, 2010, October 20, 2010 02:25, permalink

2 ratings. Login to rate!
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!
D41d8cd98f00b204e9800998ecf8427e

saikobee

November 14, 2010, November 14, 2010 04:40, permalink

1 rating. Login to rate!

Ruby already has shuffle and shuffle! built-in.

Your refactoring





Format Copy from initial code

or Cancel