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
class ApplicationController < ActionController::Base ALLOWED_REDIRECT_HOSTS = [nil, ENV.fetch("APP_HOST", "app.example.com")].freeze def store_return_to(location = request.fullpath)
Safe post-login redirects in Rails
open-redirect
session
authentication
Intermediate
9 steps
ruby
require 'set' class DirectoryWatcher def initialize(path, pattern: '**/*', interval: 1.0)
Polling for file changes in Ruby
polling
filesystem
diffing
Intermediate
7 steps
ruby
module CreditCard module_function def valid?(number)
Validating credit card numbers with Luhn
checksum
luhn-algorithm
validation
Intermediate
6 steps
ruby
class UserColor GOLDEN_RATIO_CONJUGATE = 0.618033988749895 def initialize(username)
Deriving a stable color from a username
hashing
color-theory
deterministic-mapping
Intermediate
7 steps
ruby
namespace :counter_cache do desc "Recalculate comments_count for posts after a backfill" task warm_post_comments: :environment do scope = Post.where(comments_count: nil).or(Post.where("comments_count < 0"))
Backfilling counter caches in a Rake task in Rails
counter-cache
batching
rake-tasks
Intermediate
6 steps
ruby
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 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.