2010-09-30 64 views
4

平等按照红宝石套装类的文档,“==如果两个集合相等,则返回true根据对象#EQL?红宝石套装类:套

的每对夫妇元素的定义相等。

require 'set' 
d1 = Date.today    # => Thu, 30 Sep 2010 
puts d1.object_id   # => 2211539680 
d2 = Date.today + 1   # => Fri, 01 Oct 2010 
puts d2.object_id   # => 2211522320 
set1 = Set.new([d1, d2]) 

d11 = Date.today    # => Thu, 30 Sep 2010 
puts d11.object_id   # => 2211489080 
d12 = Date.today + 1   # => Fri, 01 Oct 2010 
puts d12.object_id   # => 2211469380 
set2 = Set.new([d12, d11]) 

set1 == set2     # => true 

但是用我自己的对象,在我编写的EQL方法仅对比:这本质上可以使用Date对象,其中包含不同日期的对象,但具有相同日期设置比较平等的证明某些属性,我不能得到它的工作。

class IpDet 

    attr_reader :ip, :gateway 

    def initialize(ip, gateway, netmask, reverse) 
     @ip = ip 
     @gateway = gateway 
     @netmask = netmask 
     @reverse = reverse 
    end 

    def eql?(other) 
     if @ip = other.ip && @gateway == other.gateway 
      return true 
     else 
      return false 
     end 
    end 
end 



ipdet1 = IpDet.new(123456, 123457, 123458, 'example.com') 
ipdet2 = IpDet.new(234567, 2345699, 123458, 'nil') 

ipdet11 = IpDet.new(123456, 123457, 777777, 'other_domain.com') 
ipdet12 = IpDet.new(234567, 2345699, 777777, 'example.com') 

puts "ipdet1 is equal to ipdet11: #{ipdet1.eql?(ipdet11)}" 
puts "ipdet2 is equal to ipdet12: #{ipdet2.eql?(ipdet12)}" 


set1 = Set.new([ipdet1, ipdet2]) 
set2 = Set.new([ipdet11, ipdet12]) 

puts "set 1 is equal to set2: #{set1 == set2}" 

我从上面得到的输出是:

ipdet1 is equal to ipdet11: true 
ipdet2 is equal to ipdet12: true 
set 1 is equal to set2: false 

任何想法吗?

回答

10

当您覆盖eql?时,还总是需要覆盖hash,例如o1.eql?(o2)为真,o1.hash == o2.hash也是如此。

例如您的哈希方法看起来是这样的:

def hash 
    [@ip, @gateway].hash 
end 

而且你在eql?方法有一个错字:@ip = other.ip应该@ip == other.ip

也小stylenote:if condition then true else false end仅相当于condition,所以你eql?方法可以只被定义为

def eql?(other) 
    @ip == other.ip && @gateway == other.gateway 
end 
+0

这是伟大的,非常感谢。我脑子里想,我必须用哈希做一些事情,但不知道是什么,并且对于通过玩弄它来破坏整个储藏室感到有点紧张。所以我想现在我会读到它,所以我理解得很对。 – stephenr 2010-09-30 16:56:17