如何使用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.
更多推荐
发布评论