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
しかし、これは機能しません。誰かが私がここで間違っていることを教えてもらえますか、それともこれを行うためのより良い方法ですか?