比较单独数组中的多个对象属性

时间:2012-09-30 16:09:06

标签: ruby

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

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 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

dup_customers = 
[first_source, second_source, third_source, fourth_source]
.combination(2).flat_map{|s1, s2| s1 & s2}

答案 2 :(得分:0)

无需覆盖eql作为@pje。 uniq需要一个块(last example):

customers = [first_source ,second_source, third_source, fourth_source ].flatten
p customers.uniq{|c| c.id}

答案 3 :(得分:-1)

您可以使用Array#|(联合运营商):

customers = first_source | second_source | third_source | fourth_source

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

 ["a", "b", "c" ] | [ "c", "d", "a" ]
 #=> [ "a", "b", "c", "d" ]