覆盖Ruby的宇宙飞船运营商<=>

Eri*_*een 4 ruby sorting oop ruby-on-rails spaceship-operator

我试图覆盖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
Run Code Online (Sandbox Code Playgroud)

但这不起作用,有人可以告诉我这里做错了什么,或者更好的方法吗?

Mat*_*ggs 11

你的问题是你只是初始化任何一方的属性,另一方仍然是nil.nilArray#<=>方法中没有处理,最终导致排序.

有几种方法可以解决这个问题,首先是这样的

[self.weight.to_i, self.sweetness.to_i] <=> [other.weight.to_i, other.sweetness.to_i]
Run Code Online (Sandbox Code Playgroud)

nil.to_i给你0,让这个工作.