Ruby: get full history (all parents) of a hash node
Nested hashes could be used to represent tree structures. Here’s a code to to find a node by key and get all of its parents:
def hash_history(hash, desired_key, &block)
return false unless Hash === hash
hash.each_pair do |key, value|
if key == desired_key or hash_history(value, desired_key, &block)
yield(key, value)
return true
end
end
return false
end
hash = {
:level_1 => {
:level_2 => {
:level_3 => {
:search => 'test'
}
}
}
}
hash_history(hash, :search) { |key, value| puts key }
# prints out...
# search
# level_3
# level_2
# level_1
3 comments.
What’s the advantage of this over using a binary search tree? Is it faster?
Rudolf,
Not really an advantage over anything, this is just a code snippet illustrating how to get all parent nodes of a tree. I just found it to be a nice combo of recursion and yield.
For a similar snippet see http://snippets.dzone.com/posts/show/1908 .
Leave a Reply