0

4 つの異なるソースから重複するレコードを繰り返し処理して削除する方法を見つけようとしています。

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 を見つけてそれを使って何かを行うための方法/戦略を誰かが提案するのを手伝ってもらえますか?

4

4 に答える 4

0

Array#uniqはどうですか?

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

uniqObject#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

@pje のようにオーバーライドeqlする必要はありません。uniqブロックを取ります (最後の例):

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

Array#|を使用できます (ユニオンオペレーター):

customers = first_source | second_source | third_source | fourth_source

重複を削除しながら、2つの配列をマージした結果を返します。

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