如何调用Ruby中的超类比较器(太空船)方法?

时间:2014-01-13 17:27:37

标签: ruby spaceship-operator

我正在尝试为类而不是从超类重写比较逻辑的比较器,但由于某种原因我无法从超类比较器获得返回值。可以使用以下代码段演示此问题:

class A
  def <=>(other)
    puts "Calling A's comparator"
    return 1
  end
end

class B < A
  attr_accessor :foo

  def initialize(foo)
    @foo = foo
  end

  def <=>(other)
    if self.foo == other.foo
      c = super.<=>(other)
      puts "The return value from calling the superclass comparator is of type #{c.class}"
    else
      self.foo <=> other.foo
    end
  end
end

b1 = B.new(1)
b2 = B.new(1)
b1 <=> b2

我得到以下输出:

Calling A's comparator
The return value from calling the A's comparator is of type NilClass

我做错了什么?

2 个答案:

答案 0 :(得分:3)

Ruby中的

super并不像那样工作。 super调用此方法的超类实现。所以:

c = super(other)

您也不必提供显式参数,因为super没有参数只调用超类方法,其参数与子类实现的复活相同:

c = super

如果您需要更改为超类实现提供的参数,请仅使用显式super参数。

答案 1 :(得分:0)

super是一种基本方法,您无需在其上调用<=>

def <=>(other)
  if self.foo == other.foo
    c = super
    puts "The return value from calling the superclass comparator is of type #{c.class}"
  else
    self.foo <=> other.foo
  end
end