我正在尝试覆盖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
但这并不起作用,有人能告诉我在这里做错了什么,或者有更好的方法吗?