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

ruby-on-rails – 使用自定义规则设置

发布时间:2020-12-17 03:28:29 所属栏目:百科 来源:网络整理
导读:根据 Set doc,使用eql?比较集合中的元素. 我有一个类: class Foo attr_accessor :bar,:baz def initialize(bar = 1,baz = 2) @bar = bar @baz = baz end def eql?(foo) bar == foo.bar baz == foo.baz endend 在控制台中: f1 = Foo.newf2 = Foo.newf1.eql
根据 Set doc,使用eql?比较集合中的元素.

我有一个类:

class Foo
  attr_accessor :bar,:baz

  def initialize(bar = 1,baz = 2)
    @bar = bar
    @baz = baz
  end

  def eql?(foo)
    bar == foo.bar && baz == foo.baz
  end
end

在控制台中:

f1 = Foo.new
f2 = Foo.new
f1.eql? f2 #=> true

但…

s = Set.new
 s << f1
 s << f2
 s.size #=> 2

因为f1等于f2,所以s不应包括它们.

如何使用自定义规则设置拒绝元素?

解决方法

您链接的文档明确说明(强调我的):

The equality of each couple of elements is determined according to Object#eql?
and Object#hash,since Set uses Hash as storage.

如果你向你的类添加一个哈希方法,它返回相同的eql值?对象,它的工作原理:

# With your current class

f1,f2 = Foo.new,Foo.new
p f1.eql?(f2)
#=> true
p f1.hash==f2.hash
#=> false
p Set[f1,f2].length
#=> 2

# Fix the problem
class Foo
  def hash
    [bar,hash].hash
  end
end

f1,Foo.new
p f1.eql?(f2)
#=> true
p f1.hash==f2.hash
#=> true
p Set[f1,f2].length
#=> 1

说实话,当涉及多个值时,我从未对如何编写好的自定义哈希方法有很好的理解.

(编辑:李大同)

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

    推荐文章
      热点阅读