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
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
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
Intermediate
7 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
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-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.