如何使用Ruby的数组差异(减号)方法,`Array#-`,使用我的类?
发布时间:2020-12-17 03:54:22 所属栏目:百科 来源:网络整理
导读:我认为解释这个的最好方法是举个例子: class A attr_accessor :test def initialize(x = nil) @test = x end def ==(other) return @test == other.test endenda1 = A.new(1) # = #A:0x11b7118 @test=1a1.test # = 1a2 = A.new(1) # = #A:0x11fb0f8 @test=1
我认为解释这个的最好方法是举个例子:
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定义的方法我不知道? 解决方法
你需要覆盖eql吗?和哈希.这些是用于那些类型的集合操作的那些.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |