Skip to content

Instantly share code, notes, and snippets.

@edvardm
Last active May 22, 2020 04:17
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save edvardm/9639051 to your computer and use it in GitHub Desktop.
Save edvardm/9639051 to your computer and use it in GitHub Desktop.
Recursively symbolize ruby hash keys in a nested structure. Uses refinements instead of monkey patching Hash.
module SymbolizeHelper
extend self
def symbolize_recursive(hash)
{}.tap do |h|
hash.each { |key, value| h[key.to_sym] = transform(value) }
end
end
private
def transform(thing)
case thing
when Hash; symbolize_recursive(thing)
when Array; thing.map { |v| transform(v) }
else; thing
end
end
refine Hash do
def deep_symbolize_keys
SymbolizeHelper.symbolize_recursive(self)
end
end
end
@edvardm
Copy link
Author

edvardm commented Apr 23, 2014

Like deep_symbolize_keys in Rails, with the addition of symbolizing hashes in nested arrays.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment