Ruby - 在之前排序数组值并选择新数组

时间:2012-11-29 14:25:14

标签: ruby arrays sorting

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

# 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)

非常感谢任何形式的帮助!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

我假设分数加起来总计。

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

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]]}