سؤال

أحاول تجاوز مشغل 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

ولكن هذا لا يعمل ، هل يمكن لأحد أن يخبر ما أفعله خطأ هنا ، أو طريقة أفضل للقيام بذلك؟

هل كانت مفيدة؟

المحلول

مشكلتك هي أنك تقوم بتهيئة واحدة فقط من الخصائص على كلا الجانبين ، والآخر سيظل 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