0

我在将数组排序为升序时遇到问题,然后从数组中选择一个值放入新数组中。

# Splitting dance scores with "," and putting into arrays.
for dancers in results
  a = dancers.split(",")

  couplenumber = a[0]
  score1 = a[1]
  score2 = a[2]
  score3 = a[3]
  score4 = a[4]
  score5 = a[5]
  score6 = a[6]
  score7 = a[7]
  dancescores << Dancer.new(couplenumber, score1, score2, score3, score4, score5, score6, score7)
  # Sorts the array into ascending order, and shows the 4 lowest values.
  #p dancescores.sort.take(4)

  # Getting the m value, from picking the 4th lowest number.
  m = a[4]
  newtest = [couplenumber, m]
  coupleandscore << newtest
  coupleandscore
end
puts coupleandscore

现在它给了我新数组中的原始值,这是它应该的。但如果我尝试做

p dancescores.sort.take(4)

我会收到这个错误:

[#<Dancer:0x10604a388 @score7=5, @score3=3, @score6=6, @score2=2, @score5=1, @score1=1,     @couplenumber="34", @score4=3>]
examtest.rb:43:in `sort': undefined method `<=>' for #<Dancer:0x10604a388> (NoMethodError)

任何形式的帮助将不胜感激!

4

2 回答 2

2

你应该更准确地解释你想要做什么。

据我了解:

class Dancer

  attr_reader :number
  attr_reader :scores

  def initialize(number,scores)
    @number=number
    @scores=scores.sort
  end  
end

dancescores=[]

results.each do |result|
  scores = result.split(',')
  couplenumber = scores.shift
  dancescores << Dancer.new(couplenumber, scores)
end

# Now you can get the 4th score for each couple
dancescores.each do |dancers|
  p dancers.scores[3]
end
于 2012-11-29T15:08:35.010 回答
0

你可以<=>像这样在 Dancer 上实现

class Dancer
  def sum_scores
    @score1 + @score2 + @score3 + @score4 + @score5 + @score6 + @score7
  end
  def <=> other_dancer
    sum_scores <=> other_dancer.sum_scores
  end
end

我假设分数只是加起来总和。

更新:评分基于排序分数中的第四个值

class Dancer
  def scores
    [@score1,@score2,@score3,@score4,@score5,@score6,@score7]
  end
  def <=> other_dancer
   scores.sort[3] <=> other_dancer.scores.sort[3]
  end
end

现在在您的代码中执行以下操作:

for dancers in results
  a = dancers.split(",")

  couplenumber = a[0]
  score1 = a[1]
  score2 = a[2]
  score3 = a[3]
  score4 = a[4]
  score5 = a[5]
  score6 = a[6]
  score7 = a[7]
  dancescores << Dancer.new(couplenumber, score1, score2, score3, score4, score5, score6, score7)
end
puts dancescores.sort.map{|d| [d.couplenumber,d.scores.sort[3]]}
于 2012-11-29T14:35:27.187 回答