Ruby的数组如何.|比较要素是否相等?
发布时间:2020-12-17 03:26:06 所属栏目:百科 来源:网络整理
导读:这是一些示例代码: class Obj attr :c,true def == that p '==' that.c == self.c end def = that p '=' that.c = self.c end def equal? that p 'equal?' that.c.equal? self.c end def eql? that p 'eql?' that.c.eql? self.c endenda = Obj.newb = Obj.n
这是一些示例代码:
class Obj attr :c,true def == that p '==' that.c == self.c end def <=> that p '<=>' that.c <=> self.c end def equal? that p 'equal?' that.c.equal? self.c end def eql? that p 'eql?' that.c.eql? self.c end end a = Obj.new b = Obj.new a.c = 1 b.c = 1 p [a] | [b] 它打印2个对象,但它应该打印1个对象.没有调用任何比较方法. Array怎么样.|比较平等? 解决方法
阵列#|是使用哈希实现的.因此,为了使您的类型与它一起使用(以及使用哈希映射和散列集),您将必须实现eql? (你做了)和哈希(你没有).有意义地定义哈希的最直接的方法是返回c.hash.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读