只循环某些对象

时间:2012-12-01 07:57:06

标签: ruby arrays

我正在编写一个应该在竞赛中对竞争者进行排名和排序的程序。

# Defining class. Also sorts the array elements in ascending order.
class Dancer
attr_reader :couplenumber
attr_reader :scores
def initialize(couplenumber,scores)
@couplenumber=couplenumber
@scores=scores.sort
end 
end

# Opening file, and sorting into array. Also splits with ",".
results = File.open("danceresult.txt", "r+")
dancescores=[]
results.each do |result|
scores = result.split(',').map(&:to_i) 
couplenumber = scores.shift
dancescores << Dancer.new(couplenumber, scores)
end
dancescores.each do |dancers|
  dancers.scores
  # Prints to screen.
  puts "Couple No. #{dancers.couplenumber} got "\
       "a minimum score of #{dancers.scores[3]} or better. "\
       "Their sum is: #{dancers.scores[0..3].inject(:+)}"
end

我希望总和Their sum is: #{dancers.scores[0..3].inject(:+)}只能获得最低分数最低的人。因此,如果我们有五个竞争者,其中两个获得最低分数为2,其他三个获得最低分数为4,那么“总和部分”应该只选择最低分数为2的竞争者。是否有可能没有重做所有代码,如果是,最简单的方法是什么?

1 个答案:

答案 0 :(得分:0)

首先确定最低分数:

min_score = dancescores.map{|d| d.scores[3]}.min

然后在打印前添加条件:

dancescores.each do |dancer|
  # Prints to screen if the couple has the min_score
  if dancer.scores[3] == min_score
    puts "Couple No. #{dancer.couplenumber} got "\
       "a minimum score of #{dancer.scores[3]} or better. "\
       "Their sum is: #{dancer.scores[0..3].inject(:+)}"
  end
end

或者您可以使用select来处理那些使用min_score的舞者:

dancescores.select{|d| d[3] == min_score}.each do |dancer|
  puts "Couple No. #{dancer.couplenumber} got "\
     "a minimum score of #{dancer.scores[3]} or better. "\
     "Their sum is: #{dancer.scores[0..3].inject(:+)}"
end