Skip to content

Instantly share code, notes, and snippets.

@iamjwc
Last active May 20, 2016 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamjwc/eb4121796ef3245946bf184c344e9cd8 to your computer and use it in GitHub Desktop.
Save iamjwc/eb4121796ef3245946bf184c344e9cd8 to your computer and use it in GitHub Desktop.
Flattens hashes/arrays into a single level hash with the full json key path as a top level key. Useful for finding differences between two large manifests.
# Usage:
# (irb)> { "some" => [{"keys" => "with", "some" => ["values"]}]}.flarp
# => {"some.0.keys"=>"with", "some.0.some.0"=>"values"}
class Hash
def flarp(h = {}, prefix = nil)
each do |k, v|
new_k = [prefix, k].compact.join(".")
if v.is_a?(Array) || v.is_a?(Hash)
v.flarp(h, new_k)
else
h[new_k] = v
end
end
h
end
end
class Array
def flarp(h = {}, prefix = nil)
each_with_index do |v, i|
new_k = [prefix, i].compact.join(".")
if v.is_a?(Array) || v.is_a?(Hash)
v.flarp(h, new_k)
else
h[new_k] = v
end
end
h
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment