Help me refactor my World Cup Challenge Script

Posted by kylemac on Stack Overflow See other posts from Stack Overflow or by kylemac
Published on 2010-06-07T23:43:18Z Indexed on 2010/06/07 23:52 UTC
Read the original article Hit count: 196

I am setting up a World Cup Challenge between some friends, and decided to practice my Ruby and write a small script to automate the process.

The Problem:

  • 32 World Cup qualifiers split into 4 tiers by their Fifa ranking
  • 8 entries
  • Each entry is assigned 1 random team per tier
  • Winner takes all :-)

I wrote something that suffices yet is admittedly brute force. But, in my attempt to improve my Ruby, I acknowlege that this code isn't the most elegant solution around - So I turn to you, the experts, to show me the way.

It may be more clear to check out this gist - https://gist.github.com/91e1f1c392bed8074531

My Current (poor) solution:

require 'yaml'

@teams = YAML::load(File.open('teams.yaml'))
@players = %w[Player1 Player2 Player3 Player4 Player5 Player6 Player7 Player8]

results = Hash.new
players = @players.sort_by{rand}

players.each_with_index do |p, i|
  results[p] = Array[@teams['teir_one'][i]]
end

second = @players.sort_by{rand}
second.each_with_index do |p, i|
  results[p] << @teams['teir_two'][i]
end

third = @players.sort_by{rand}
third.each_with_index do |p, i|
  results[p] << @teams['teir_three'][i]
end

fourth = @players.sort_by{rand}
fourth.each_with_index do |p, i|
  results[p] << @teams['teir_four'][i]
end

p results

I am sure there is a better way to iterate through the tiers, and duplicating the @players object ( dup() or clone() maybe?)

So from one Cup Fan to another, help me out.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about refactoring