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

时间:2010-06-17 04:10:12

标签: ruby-on-rails ruby oop sorting 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

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

2 个答案:

答案 0 :(得分:11)

您的问题是您只是初始化其中一个属性,另一个仍然是nilnil方法未处理Array#<=>,最终导致排序。

有几种方法可以首先解决这个问题

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

nil.to_i为您提供了0,这将使其发挥作用。

答案 1 :(得分:-1)

可能迟到了,不过......

添加以下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