Skip to content

Instantly share code, notes, and snippets.

@dbrady
Created May 12, 2015 13:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dbrady/121ceecac3bef9cdd3b0 to your computer and use it in GitHub Desktop.
Save dbrady/121ceecac3bef9cdd3b0 to your computer and use it in GitHub Desktop.
hash_to_breadcrumb - turn a hash containing items, arrays, or nested hashes into a flattened list of "breadcrumbs" -- e.g. the path through the hash to get to the last value in the list.
# hash_to_breadcrumbs
#
# hash_to_breadcrumb - turn a hash containing items, arrays, or nested hashes
# into a flattened list of "breadcrumbs" -- e.g. the path through the hash to
# get to the last value in the list.
hash = {
a: 1,
b: [2, 3, 4],
c: {
d: 5,
e: [6,7,8],
f: {
g: 9,
h: [10, 11],
i: {
j: 12
}
}
}
}
expected_breadcrumbs = [
[:a, 1],
[:b, 2],
[:b, 3],
[:b, 4],
[:c, :d, 5],
[:c, :e, 6],
[:c, :e, 7],
[:c, :e, 8],
[:c, :f, :g, 9],
[:c, :f, :h, 10],
[:c, :f, :h, 11],
[:c, :f, :i, :j, 12]
]
def hash_to_breadcrumbs(object, parent=[])
ray = []
if object.is_a? Hash
object.each do |key, val|
ray += hash_to_breadcrumbs val, parent.dup + [key]
end
elsif object.is_a? Array
object.each do |elem|
ray += hash_to_breadcrumbs elem, parent
end
else
ray << parent.dup + [object]
end
ray
end
puts '-' * 80
puts "Expected:"
puts '-' * 10
puts expected_breadcrumbs.map(&:inspect)
actual_breadcrumbs = hash_to_breadcrumbs(hash)
puts '-' * 80
puts "Actual:"
puts '-' * 10
puts actual_breadcrumbs.map(&:inspect)
puts '-' * 80
puts "Are they equal?"
puts(if actual_breadcrumbs == expected_breadcrumbs
"YES YES YES OH WOOT YES YES YESSSSS!!!! WOOOOO!!!!"
else
"Nope."
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment