我想重载Ruby的< =>(飞船)运营商排序苹果和橙子,这样苹果先按重量排序,再按橙色排序,按甜味排序。像这样:凌驾Ruby的飞船运营商<=>
module Fruity
attr_accessor :weight, :sweetness
def <=>(other)
# use Array#<=> to compare the attributes
[self.weight, self.sweetness] <=> [other.weight, other.sweetness]
end
include Comparable
end
class Apple
include Fruity
def initialize(w)
self.weight = w
end
end
class Orange
include Fruity
def initialize(s)
self.sweetness = s
end
end
fruits = [Apple.new(2),Orange.new(4),Apple.new(6),Orange.new(9),Apple.new(1),Orange.new(22)]
p fruits
#should work?
p fruits.sort
但是这不起作用,有人可以告诉我在这里做错了什么,或者更好的方法来做到这一点?
作业的身体吗? :)... – devios1 2010-06-17 04:15:08
更新:事实证明,我是这样做的错误方式。提示:答案在于 - http://blog.hasmanythrough.com/2008/8/17/sorting-things-out – 2011-12-10 00:22:04