加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby Set类:集合的相等性

发布时间:2020-12-17 03:58:11 所属栏目:百科 来源:网络整理
导读:根据 Ruby Set类的文档,“==如果两个集合相等则返回true.每个元素的相等性是根据Object#eql?定义的. 可以使用Date对象来演示其本质,其中包含不同Date对象但具有相同日期的集合比较相等: require 'set'd1 = Date.today # = Thu,30 Sep 2010puts d1.object_i
根据 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,'nil')

ipdet11 = IpDet.new(123456,777777,'other_domain.com')
ipdet12 = IpDet.new(234567,'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?时,你也总是需要覆盖哈希,如果o1.eql?(o2)为真,那么o1.hash == o2.hash也是如此.

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

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

你的eql中也有拼写错误吗?方法:@ip = other.ip应该是@ip == other.ip.

也是一个次要的样式:如果条件然后为真,否则假结束等同于条件,所以你的eql?方法可以定义为

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读