2016-06-13 90 views
-2

我想按我的对象(分数)的某个方面进行排序。这是我迄今为止,但我收到的错误消息,如“未定义的方法评分”。Ruby sort_by混淆

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 
+1

您有'@ score'实例变量,但没有'score'方法。 –

+0

欢迎来到Stack Overflow。请阅读“[mcve]”。如果你的代码正确缩进,它会帮你找出问题。你的代码不会被Ruby接受,因为它缺少多个'end'语句。另外,调用一个类“对象”是一个非常糟糕的主意。首先,类应该是CamelCase,所以它应该是Object,但已经有一个[Object](http://ruby-doc.org/core-2.3.1/Object.html)类,并且覆盖它是一个真是糟糕的主意。 –

+0

你确实需要清除这段代码,这不是有效的Ruby。此外,约定认为方法有'sort_by_score'这样的名称,而空参数被省略,即'()'几乎从不指定。在数组内部分配未使用的变量同样令人困惑和混乱。最重要的是,不要调用你的类'object',因为'Object'是所有Ruby对象的基础。 – tadman

回答

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] 
+0

我来自Java/Python的世界,你会说 “attr_reader:score” 有点像分数值的“getter”方法吗? –

+0

@DannyTobackdtdirt - 是的。还有attr_writer(setter)和attr_accessor(getter/setter)。 – seph

0

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

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

应该做的伎俩。

0
R = Struct.new(:confusion) 

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