ruby
27 lines · 7 steps
Recursively camelizing nested Ruby data
A small class that walks arbitrarily nested hashes and arrays, converting every snake_case key to camelCase.
Explained by
highlit
1class KeyTransformer
2 def self.camelize(data)
3 new.camelize(data)
4 end
5
6 def camelize(data)
7 case data
8 when Hash
9 data.each_with_object({}) do |(key, value), result|
10 result[camelize_key(key)] = camelize(value)
11 end
12 when Array
13 data.map { |element| camelize(element) }
14 else
15 data
16 end
17 end
18
19 private
20
21 def camelize_key(key)
22 string = key.to_s
23 head, *rest = string.split("_")
24 camelized = [head, *rest.map(&:capitalize)].join
25 key.is_a?(Symbol) ? camelized.to_sym : camelized
26 end
27end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Recursion lets one method handle arbitrarily deep nesting by delegating each sub-structure back to itself.
- 2A convenience class method (`self.camelize`) can hide the `new.camelize` instantiation from callers.
- 3Preserving the key's original type — symbol or string — keeps the transformed data faithful to its input.
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
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
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/recursively-camelizing-nested-ruby-data-explained-ruby-24d1/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.