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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Passing a block to uniq lets you define equality on a derived key instead of the whole object.
- 2Normalizing values before comparing catches duplicates that differ only in casing or formatting.
- 3Returning an array from the uniq block creates a composite key across multiple fields.
Related explainers
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/deduplicating-contacts-with-enumerable-uniq-explained-ruby-e87f/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.