我正在建立一些朋友之间的世界杯挑战赛,并决定练习我的Ruby并编写一个小脚本来自动化这个过程。
问题:
我写了一些足够的东西,但无疑是蛮力。但是,在我尝试改进我的Ruby时,我承认这段代码并不是最优雅的解决方案 - 所以我请求专家给我指路。
可以更清楚地看一下这个要点 - https://gist.github.com/91e1f1c392bed8074531
我的当前(差)解决方案:
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
我确信有更好的方法来遍历各层,并重复@players对象(dup()
或clone()
可能?)
所以从一个球迷到另一个球迷,帮助我。
答案 0 :(得分:2)
我还在学习Ruby,但这是一次尝试:
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(' ') }