在Ruby中如何调用超类比较器(spaceship)方法?
我试图在不重写超类的比较逻辑的情况下为类创建一个比较器,但是由于某些原因,我无法从超类比较器获取返回值。此问题可通过以下代码片段演示:在Ruby中如何调用超类比较器(spaceship)方法?,ruby,spaceship-operator,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 <=&
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
我做错了什么?
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
def(其他)
如果self.foo==other.foo
c=超级
puts“调用超类比较器的返回值的类型为#{c.class}”
其他的
self.foo其他.foo
结束
结束
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
def(其他)
如果self.foo==other.foo
c=超级
puts“调用超类比较器的返回值的类型为#{c.class}”
其他的
self.foo其他.foo
结束
结束
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
def(其他)
如果self.foo==other.foo
c=超级
puts“调用超类比较器的返回值的类型为#{c.class}”
其他的
self.foo其他.foo
结束
结束
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
def(其他)
如果self.foo==other.foo
c=超级
puts“调用超类比较器的返回值的类型为#{c.class}”
其他的
self.foo其他.foo
结束
结束
Ruby中的超级
super
不是这样工作的super
调用此方法的超类实现。因此:
您也不必提供显式参数,因为没有参数的super
只需使用与恢复的子类实现相同的参数调用超类方法:
c = super
如果需要更改给定给超类实现的参数,则仅使用显式的
super
参数。super
在Ruby中不是这样工作的super
调用此方法的超类实现。因此:
您也不必提供显式参数,因为没有参数的super
只需使用与恢复的子类实现相同的参数调用超类方法:
c = super
如果需要更改给定给超类实现的参数,则仅使用显式的
super
参数。super
在Ruby中不是这样工作的super
调用此方法的超类实现。因此:
您也不必提供显式参数,因为没有参数的super
只需使用与恢复的子类实现相同的参数调用超类方法:
c = super
如果需要更改给定给超类实现的参数,则仅使用显式的
super
参数。super
在Ruby中不是这样工作的super
调用此方法的超类实现。因此:
您也不必提供显式参数,因为没有参数的super
只需使用与恢复的子类实现相同的参数调用超类方法:
c = super
如果需要更改给定给超类实现的参数,则仅使用显式的
super
参数。参数在调用super
时自动提供,无需指定其他参数。参数在调用super
时自动提供,无需指定其他参数。调用super
时自动提供参数,无需指定其他参数。调用super
时自动提供参数,无需指定其他参数。