ruby 19 lines · 4 steps

Deduplicating contacts with Enumerable#uniq

How a custom block on uniq lets you collapse duplicate records by a normalized identity rather than exact equality.

Explained by highlit
1class ContactImporter
2 def initialize(rows)
3 @rows = rows
4 end
5 
6 def dedupe
7 @rows.uniq { |row| normalized_email(row) }
8 end
9 
10 def dedupe_by_composite
11 @rows.uniq { |row| [normalized_email(row), row[:phone].to_s.gsub(/\D/, "")] }
12 end
13 
14 private
15 
16 def normalized_email(row)
17 row[:email].to_s.strip.downcase
18 end
19end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Passing a block to uniq lets you define equality on a derived key instead of the whole object.
  2. 2Normalizing values before comparing catches duplicates that differ only in casing or formatting.
  3. 3Returning an array from the uniq block creates a composite key across multiple fields.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Deduplicating contacts with Enumerable#uniq — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code