2010-09-30 67 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