ruby
44 lines · 7 steps
Diffing two hashes in Ruby
A small class that reports which keys were added, removed, or changed between two hashes.
Explained by
highlit
1class HashDiff
2 Change = Struct.new(:from, :to)
3
4 def self.call(before, after)
5 new(before, after).call
6 end
7
8 def initialize(before, after)
9 @before = before || {}
10 @after = after || {}
11 end
12
13 def call
14 {
15 added: added,
16 removed: removed,
17 changed: changed
18 }
19 end
20
21 private
22
23 attr_reader :before, :after
24
25 def added
26 (after.keys - before.keys).each_with_object({}) do |key, memo|
27 memo[key] = after[key]
28 end
29 end
30
31 def removed
32 (before.keys - after.keys).each_with_object({}) do |key, memo|
33 memo[key] = before[key]
34 end
35 end
36
37 def changed
38 (before.keys & after.keys).each_with_object({}) do |key, memo|
39 next if before[key] == after[key]
40
41 memo[key] = Change.new(before[key], after[key])
42 end
43 end
44end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Array subtraction and intersection on hash keys cleanly express added, removed, and shared keys.
- 2each_with_object builds a result hash in one pass without a separate accumulator variable.
- 3A tiny Struct gives changed values a readable from/to shape instead of an opaque pair.
Related explainers
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
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
ruby
class SnippetHighlighter CONTEXT_RADIUS = 60 MAX_TERMS = 8
Building search-result snippets in Ruby
regular-expressions
text-processing
search
Intermediate
9 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/diffing-two-hashes-in-ruby-explained-ruby-6fd0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.