Ruby sort_by混乱

时间:2016-06-13 20:57:21

标签: ruby-on-rails ruby sorting

我正在尝试按对象(得分)的某个方面进行排序。这是我到目前为止,但我收到错误消息,如“未定义的方法得分”。

class object
    def initialize(likes, comments, score)
        @no_of_likes=likes
        @no_of_comments=comments
        @score =score
    def calculateScore
        #Assigns a score to each element of the array, based off of            algorithm
        @score = (@no_of_likes + @no_of_comments)
    end
def sortByScore()

    arr = [o1 =Object.new(40, 35, 0), o2 =Object.new(100, 2, 0), o3 = Object.new(1, 150, 0)]

    for obj in arr
        obj.calculateScore
    end
    #sorts by score
    arr = ar.sort_by &:score
    puts arr.inspect
end

3 个答案:

答案 0 :(得分:2)

我将你的班级改名为Obj,对象不是一个好名字。 Obj也不好。试着给这个类命名一些描述你最近的东西(Scorekeeper怎么样?)。

class Obj
  attr_reader :score

  def initialize(likes, comments, score)
    @no_of_likes = likes
    @no_of_comments = comments
    @score = score
  end

  # Assigns a score to each element of the array, based off of algorithm
  def calculateScore
    @score = (@no_of_likes + @no_of_comments)
  end
end

注意添加的行:

  attr_reader :score

这相当于:

  def score
    @score
  end

这是你缺少/未定义的方法:

arr = [Obj.new(40, 35, 0), Obj.new(1, 150, 0), Obj.new(100, 2, 0)]
arr.map(&:score)
 => [0, 0, 0]

arr.each { |obj| obj.calculateScore }
arr.map(&:score)
 => [75, 151, 102] 

arr = arr.sort_by(&:score)
arr.map(&:score)
 => [75, 102, 151] 

答案 1 :(得分:0)

如果您有这些对象的集合,

@collection.sort_by{|object| object.score} 

应该做的伎俩。

答案 2 :(得分:0)

R = Struct.new(:confusion)

Ruby = Array.new(9){R.new(rand)}
sorted = Ruby.sort_by(&:confusion)