gpt4 book ai didi

Ruby 设置类 : equality of sets

转载 作者:数据小太阳 更新时间:2023-10-29 07:03:21 25 4
gpt4 key购买 nike

根据 Ruby Set 类的文档,“== 如果两个集合相等,则返回 true。每对元素的相等性根据 Object#eql? 定义。

可以使用 Date 对象来演示其本质,其中包含不同 Date 对象但具有相同日期的集合比较相等:

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?方法只比较某些属性,我不能让它工作。

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

有什么想法吗?

最佳答案

当你覆盖 eql? 时,你也总是需要覆盖 hash 使得如果 o1.eql?(o2) 为真, o1.hash == o2.hash 也是如此。

例如,您的哈希方法可能如下所示:

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

您的 eql? 方法中还有一个错字:@ip = other.ip 应该是 @ip == other.ip .

还有一个小风格注释:if condition then true else false end 仅相当于 condition,所以你的 eql? 方法可以是定义为

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

关于Ruby 设置类 : equality of sets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3832703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com