質問

リンゴとオレンジを並べ替えるために、ルビーの<=>(宇宙船)オペレーターをオーバーライドして、リンゴが最初に重量で並べ替え、2番目に甘さでソートされます。そのようです:

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

しかし、これはうまくいきません、誰かが私がここで間違っていることを伝えることができますか、それともこれを行うより良い方法ですか?

役に立ちましたか?

解決

あなたの問題は、どちらの側のプロパティの1つだけを初期化していることです。もう1つはまだ nil. nil で処理されていません Array#<=> メソッドは、ソートを殺すことになります。

最初に問題を処理する方法はいくつかあります

[self.weight.to_i, self.sweetness.to_i] <=> [other.weight.to_i, other.sweetness.to_i]

nil.to_i あなたにあげる 0, 、これが機能するようになります。

他のヒント

おそらく遅く、それにもかかわらず...

次のMonkeypatchを追加します

class Array
  def to_i(default=Float::INFINITY)
    self.map do |element|
      element.nil? ? default : element.to_i
    end
  end
end

の体を変えます Fruity::<=> to

[self.weight, self.sweetness].to_i <=> [other.weight, other.sweetness].to_i
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top