2009-11-07 22 views
1

我知道我可以使用像User.sort {| a,b | a.attribute < => b.attribute}或User.find和order,但它是一种类似于Java中的可比接口的方式,所以每次我对User对象进行排序时,它都会对预定义的属性进行排序。在轨道中排序对象的集合?

谢谢,通过定义你的对象<=>方法

回答

4

你可以这样做。这样的话,你应该能够只是说:collection.sort无损排序或collection.sort!就地排序:

因此,这里的例子:

class A 
    def <=>(other) 
     # put sorting logic here 
    end 
end 

和更完整的一个:

class A 
    attr_accessor :val 
    def initialize 
     @val = 0 
    end 

    def <=>(other) 
     return @val <=> other.val 
    end 
end 

a = A.new 
b = A.new 
a.val = 5 
b.val = 1 
ar = [a,b] 
ar.sort! 
ar.each do |x| 
    puts x.val 
end 

这将输出15

+0

我刚刚发现ruby具有Comparable模块,我们可以使用定义<=>的一种方法实现所有比较操作。使用它只需在任何你想要的类中包含Comparable。 – sarunw 2009-11-07 16:49:48

+0

这是一回事。如果包含Comparable,则仍需要定义自己的'<=>'方法。问题是,你只会有一行额外的代码,这些代码不会用于任何目的。 – Geo 2009-11-07 17:03:38

+1

它确实起到了一些作用,这是为了让您的对象具有比较操作(< <= == > =>)。与其单独定义它,您只需包含Comparable并定义您自己的<=>方法。 – sarunw 2009-11-07 17:33:27