gpt4 book ai didi

ruby - 如果父类已经有 'Comparable',如何实现 '=='

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:09 26 4
gpt4 key购买 nike

我有一个库类,它提供了平等和不平等的方法。我正在从中派生另一个类,与父类不同,它引入了一个排序关系,即要求派生类的两个元素是有意义的,哪个元素较小。特别是派生类的对象数组可以排序。

我的第一个方法是

class MyClass < LibraryClass
def <(other)
...
end
def <=>(other)
return 0 if self == other
return -1 if self < other
return 1
end
# code for operators > <= >= is not shown here....
end

这似乎可行,但我认为用 [原文如此] Comparable 可能会更好,因为这会免费提供大量其他方法。

  1. Comparable的描述说我必须实现 <=>运算符,以及其他运算符,包括 ==!=然后将自动执行。但是,我已经对 == 感到满意了来自父类的运算符,因此不应生成新的相等方法。

  2. 我想使用 == 来测试相等性来自父类的运算符。如果我实现 <=>运算符,和 Comparable实现一个 ==我的运算符 <=>运算符,我最终会进行递归调用。

对于表达式self == other ,如何指定 ==应该调用父类的运算符?

最佳答案

include使 Comparable MyClass 的父类(super class)和 LibraryClass Comparable 的父类(super class).所以,执行 ==Comparable覆盖 == 的实现在 LibraryClass .

然后您可以做的是覆盖 == 再次 MyClassLibraryClass 中的版本相同:

class MyClass < LibraryClass
include Comparable

def <=>(other)
# whatever
end

define_method(:==, LibraryClass.public_instance_method(:==))
end

关于ruby - 如果父类已经有 'Comparable',如何实现 '==',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44497095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com