Skip to content

Instantly share code, notes, and snippets.

@Hampei
Created June 9, 2020 08:02
Show Gist options
  • Save Hampei/0efee2f0c749bfb1b690bb0c85ec6229 to your computer and use it in GitHub Desktop.
Save Hampei/0efee2f0c749bfb1b690bb0c85ec6229 to your computer and use it in GitHub Desktop.
# block gets key, value of each hash entry whose value is not a Hash or Array,
# should return a new key and value for that entry.
def deep_transform(obj, &block)
case obj
when Hash
obj.map do |key, val|
case val
when Hash, Array
[key, deep_transform(val, &block)]
else
yield key, val
end
end.to_h
when Array
obj.map { |val| deep_transform(val, &block) }
else
obj
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment