开发者

Help me refactor my World Cup Challenge Script

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.


I'm still learning Ruby too, but here's an attempt:

require 'yaml'

tiers   = YAML::load(File.open('world_cup_tiers.yaml'))
players = %w[P1 P2 P3 P4 P5 P6 P7 P8]

draws = Hash.new { |h,k| h[k] = [] }

tiers.each do |tier, teams|
    players.zip(teams.sort_by{rand}).each do |tuple|
        player, team = tuple
        draws[player].push(team)
    end
end

players.each { |player| puts [player, draws[player]].join(' ') }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜