Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Recursively symbolize ruby hash keys in a nested structure. Uses refinements instead of monkey patching Hash.
# # usage:
# require_relative 'lib/stringify_helper'
# extend StringifyHelper
# using StringifyHelper
#
# { test: { foo: "bar" } }.deep_stringify_keys #=> \
# # { "test" => { "foo" => "bar" } }
module StringifyHelper
extend self
def stringify_recursive(hash)
{}.tap do |h|
hash.transform_keys(&:to_s).each do |key, value|
value = case value
when Hash then stringify_recursive value
when Array then value.map { |elem| elem.is_a?(Hash) ? stringify_recursive(elem) : elem }
else
value
end
h[key] = value
end
end
end
refine Hash do
def deep_stringify_keys
StringifyHelper.stringify_recursive self
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment