0

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

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

我究竟做错了什么?

4

2 回答 2

3

super in Ruby doesn't work like that. super calls the superclasses implementation of this method. So:

c = super(other)

You also don't have to provide the explicit argument, as super with no arguments just calls the superclass method with the same arguments as the subclass implementation revived:

c = super

Only use explicit super arguments if you need to change the arguments given to the superclass implementation.

于 2014-01-13T17:43:00.503 回答
0

super is a base method, you don't need to call <=> on it:

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 
于 2014-01-13T17:42:59.473 回答