2012-09-30 5 views
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 

을 시도하지만이 정말 작동하지 않았다.

누군가이 4 가지 컬렉션을 탐색하고 동일한 ID를 가진 고객 ID를 찾는 방법을 제안 할 수 있습니까?

+0

중복이있는 경우, 당신은/모든 소스, 또는 모든 하나, 또는 없음을 제외한 모두에서 제거 하시겠습니까? 중복을 제거하는 대신 검색을 원한다는 의미입니까? – sawa

+0

또한, 두 개의 Customer 객체가 동일한'id' 속성을 가지고 있다면 중복 객체라고 생각하십니까? – pje

답변

0

방법에 대한 Array#uniq? 이 방법이 작동하려면, 그래서 Object#eql?를 사용하여 요소 현명한 비교하여

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

uniq 폐기 중복, 당신은 Customer#eql?를 구현해야합니다. @pje이처럼

class Customer 
    def eql?(other) 
    id == other.id #or however you define equality 
    end 
end 
+0

안녕하세요, 빠른 응답 주셔서 감사합니다. 나는 그것을 시도하고 나에게 uniq 결과를 돌려주지는 않습니다 ... 배열이 객체로 구성되어 있기 때문에 ... 그리고 나는 방법이 필요합니다. 배열에서 각각을 반복하고 uniq 결과로 돌아옵니다. –

+0

굉장한 pje. .. 지금 이것에서 약간의 감각이있다.. 그리고 당신은 나의 머리 환호에 약간의 생각을했다. –

-1

당신은 Array#| (UNION 연산자)를 사용할 수 있습니다 :

customers = first_source | second_source | third_source | fourth_source 

그것은 제거 중복 동안 두 배열의 합병의 결과를 반환합니다

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

나는 오히려 혼란 스럽다, 왜 anonym downvote? (확실히 답변입니다) – Eureka

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

재정 eql 필요가 없습니다. uniq가 블록 (last example)를 취합니다

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