0

我试图找出一种方法来迭代并从四个不同的来源中删除重复记录。

first_source = [#<Customer:0x007f911e307ad0 @id="123", @name="Whitehall">,#       <Customer:0x007f911e307ad0 @id="124", @name="Whitehall">#<Customer:0x007f911e307ad0 @id="125", @name="Whitehall">]
second_source =  [#<Customer:0x007f911e307ad0 @id="5000", @name="Whitehall">,#<Customer:0x007f911e307ad0 @id="5500", @name="Whitehall">#<Customer:0x007f911e307ad0 @id="123", @name="Whitehall">]
third_source =  [#<Customer:0x007f911e307ad0 @id="800", @name="Whitehall">,#<Customer:0x007f911e307ad0 @id="5000", @name="Whitehall">#<Customer:0x007f911e307ad0 @id="124", @name="Whitehall">]
fourth_source =  [#<Customer:0x007f911e307ad0 @id="4300", @name="Whitehall">,#<Customer:0x007f911e307ad0 @id="800", @name="Whitehall">#<Customer:0x007f911e307ad0 @id="125", @name="Whitehall">]

我试过

customers = []

dup_customers = first_source + second_source + third_source + fourth_source

dup_customers.combination(2).each do |cs1, cs2|
  customers << cs1 unless cs1.id != cs2.id
end

但这确实行不通。

有人可以帮我建议一种方法/策略来遍历这四个集合并找到相等的客户 ID,然后用它做点什么吗?

4

4 回答 4

0

Array#uniq怎么样?

customers = (first_source + second_source + third_source + fourth_source).uniq

uniq使用Object#eql通过逐元素比较丢弃重复项?,因此要使此方法起作用,您需要实现Customer#eql?.

class Customer
  def eql?(other)
    id == other.id #or however you define equality
  end
end
于 2012-09-30T16:17:20.997 回答
0
dup_customers = 
[first_source, second_source, third_source, fourth_source]
.combination(2).flat_map{|s1, s2| s1 & s2}
于 2012-09-30T16:53:12.720 回答
0

eql不需要像@pje 那样覆盖。uniq接受一个块(最后一个例子):

customers = [first_source ,second_source, third_source, fourth_source ].flatten
p customers.uniq{|c| c.id}
于 2012-09-30T20:40:33.693 回答
-1

您可以使用数组#| (联合运算符):

customers = first_source | second_source | third_source | fourth_source

它在删除重复项的同时返回两个数组合并的结果:

 ["a", "b", "c" ] | [ "c", "d", "a" ]
 #=> [ "a", "b", "c", "d" ]
于 2012-09-30T16:13:57.027 回答