如何使用Ruby的数组差异(减号)方法,`Array#

编程入门 行业动态 更新时间:2024-10-13 10:23:25
如何使用Ruby的数组差异(减号)方法,`Array#-`,与我的类一起工作?(How do I make Ruby's Array difference (minus) method, `Array#-`, work with my classes?)

我认为解释这个的最好方法是举个例子:

class A attr_accessor :test def initialize(x = nil) @test = x end def ==(other) return @test == other.test end end a1 = A.new(1) # => #<A:0x11b7118 @test=1> a1.test # => 1 a2 = A.new(1) # => #<A:0x11fb0f8 @test=1> a2.test # => 1 a1 == a2 # => true [a1].include?(a2) # => true [a1] - [a2] # => [#<A:0x11b7118 @test=1>]

在这个例子中,我将如何让[a1] - [a2]返回一个空数组,像其他任何Ruby类所期望的那样? 是否有一些我必须为A定义的方法我不知道?

I think the best way to explain this is with an example:

class A attr_accessor :test def initialize(x = nil) @test = x end def ==(other) return @test == other.test end end a1 = A.new(1) # => #<A:0x11b7118 @test=1> a1.test # => 1 a2 = A.new(1) # => #<A:0x11fb0f8 @test=1> a2.test # => 1 a1 == a2 # => true [a1].include?(a2) # => true [a1] - [a2] # => [#<A:0x11b7118 @test=1>]

In this example, how would I get [a1] - [a2] to return an empty array, as one would expect it to for any other Ruby class? Is there some method that I have to define for A that I'm missing?

最满意答案

你需要覆盖eql? 和hash 。 这些是用于那些类型的集合操作的那些。

You need to override eql? and hash. These are the ones that are used for those kinds of set operations.

更多推荐

本文发布于:2023-08-07 02:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1459071.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:减号   数组   如何使用   差异   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!