ruby
28 lines · 8 steps
Recursively merging nested config hashes in Ruby
A module that deep-merges two hashes, combining nested hashes and arrays instead of clobbering them.
Explained by
highlit
1module ConfigMerge
2 module_function
3
4 def deep_merge(base, override)
5 base.merge(override) do |_key, base_val, override_val|
6 if base_val.is_a?(Hash) && override_val.is_a?(Hash)
7 deep_merge(base_val, override_val)
8 elsif base_val.is_a?(Array) && override_val.is_a?(Array)
9 (base_val + override_val).uniq
10 else
11 override_val
12 end
13 end
14 end
15
16 def deep_merge!(base, override)
17 override.each do |key, override_val|
18 base_val = base[key]
19 base[key] =
20 if base_val.is_a?(Hash) && override_val.is_a?(Hash)
21 deep_merge!(base_val, override_val)
22 else
23 override_val
24 end
25 end
26 base
27 end
28end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Passing a block to `merge` lets you decide per-key how conflicting values combine instead of blindly overwriting.
- 2Recursing into nested hashes lets a merge preserve deep structure rather than replacing whole subtrees.
- 3Offering both a pure and a bang variant gives callers the choice between safety and in-place efficiency.
Related explainers
ruby
class WebhookSignatureConstraint def initialize(provider) @provider = provider end
Verifying webhook signatures with Rails routing constraints
routing constraints
hmac
webhooks
Advanced
7 steps
java
public final class EmailNormalizer { private static final Pattern EMAIL_PATTERN = Pattern.compile( "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
Normalizing email addresses in Java
validation
regex
normalization
Intermediate
8 steps
ruby
module UniqueJob extend ActiveSupport::Concern class_methods do
Deduplicating Active Job enqueues in Rails
concurrency
idempotency
caching
Advanced
9 steps
php
<?php namespace App\Http\Requests\DataObjects;
Typed request DTOs in Laravel
data-transfer-object
validation
immutability
Intermediate
6 steps
ruby
class OrderMailerPreview < ActionMailer::Preview def confirmation OrderMailer.confirmation(sample_order) end
Previewing Rails mailers with sample data
mailer-previews
test-fixtures
in-memory-objects
Beginner
6 steps
typescript
type Masker = (value: string) => string; const maskEmail: Masker = (value) => { const [local, domain] = value.split("@");
Recursively masking sensitive data for logs
recursion
regex
data-masking
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/recursively-merging-nested-config-hashes-in-ruby-explained-ruby-d7fc/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.