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
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 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
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
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
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.