小编Lar*_*ter的帖子

Ruby #union on Array 反应非常奇怪

我喜欢使用 Array#union 或 #| 方法返回已删除重复项的对象数组。我在我的班级中有一个自定义实现eql?。如果我这样做的话,就会有一种非常奇怪的行为。最多 8 个元素,联合工作正常,但元素更多时,重复项不会被删除。这实际上是红宝石的错误还是我错过了什么?

class A
  attr_accessor :name

  def initialize(name)
    self.name = name
  end

  def eql?(other)
    other.name.eql?(name)
  end
end

as = names.map { |name| A.new(name) }
bs = names.map { |name| A.new(name) }

as | bs
=>
[#<A:0x00007fe503692388 @name="a">,
 #<A:0x00007fe503692310 @name="b">,
 #<A:0x00007fe5036922e8 @name="c">,
 #<A:0x00007fe5036922c0 @name="d">,
 #<A:0x00007fe503692298 @name="e">,
 #<A:0x00007fe503692270 @name="f">,
 #<A:0x00007fe503692248 @name="g">,
 #<A:0x00007fe503692220 @name="h">,
 #<A:0x00007fe5036921f8 @name="i">,
 #<A:0x00007fe5036921d0 @name="j">,
 #<A:0x00007fe5036921a8 @name="k">,
 #<A:0x00007fe503692180 @name="l">,
 #<A:0x00007fe5035732e0 @name="a">,
 #<A:0x00007fe5035732b8 @name="b">,
 #<A:0x00007fe503573290 @name="c">,
 #<A:0x00007fe503573268 @name="d">,
 #<A:0x00007fe503573240 @name="e">,
 #<A:0x00007fe503573218 @name="f">,
 #<A:0x00007fe5035731f0 @name="g">, …
Run Code Online (Sandbox Code Playgroud)

ruby arrays union

2
推荐指数
1
解决办法
82
查看次数

标签 统计

arrays ×1

ruby ×1

union ×1