Created
June 5, 2013 22:14
-
-
Save perplexes/5717773 to your computer and use it in GitHub Desktop.
Hash/Array Tree searcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# > n = Node.find_where(terms2){|v| !v["Section"].empty?} | |
# => #<Node key="Sections" value=Hash children=1> | |
# > puts n.path | |
# => [0]["Departments"]["Department"][3]["Courses"]["Course"][1]["Sections"] | |
class Node | |
attr_reader :parent, :key, :value, :children | |
def initialize(parent, key, value) | |
@parent = parent | |
@key = key | |
@value = value | |
@children = case value | |
when Hash | |
value.map{|k, v| self.class.new(self, k, v)} | |
when Enumerable | |
value.map.with_index{|e, i| self.class.new(self, i, e)} | |
else | |
[] | |
end | |
end | |
def self.find_where(obj, &block) | |
new(nil, nil, obj).find_where(&block) | |
end | |
def find_where(&block) | |
if block.call(value) | |
self | |
else | |
for child in children | |
return node if node = child.find_where(&block) | |
end | |
nil | |
end | |
rescue | |
for child in children | |
return node if node = child.find_where(&block) | |
end | |
nil | |
end | |
def inspect | |
"#<Node key=#{key.inspect} value=#{value.class} children=#{children.size} parent=#{parent ? parent.key : 'nil'}>" | |
end | |
def path | |
if parent | |
parent.path + "[#{key.inspect}]" | |
else | |
"" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment