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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Recursion lets one method handle arbitrarily deep nesting by delegating each sub-structure back to itself.
  2. 2A convenience class method (`self.camelize`) can hide the `new.camelize` instantiation from callers.
  3. 3Preserving the key's original type — symbol or string — keeps the transformed data faithful to its input.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Recursively camelizing nested Ruby data — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code