我想重載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