我有以下的類叫做樹是建立一個簡單的樹變化樹形結構紅寶石使用嵌套哈希
class Tree
attr_accessor :children, :node_name
def initialize(name, children=[])
@children = children
@node_name = name
end
def visit_all(&block)
visit &block
children.each {|c| c.visit_all &block}
end
def visit(&block)
block.call self
end
end
ruby_tree = Tree.new("grandpa",
[Tree.new("dad", [Tree.new("child1"), Tree.new("child2")]),
Tree.new("uncle", [Tree.new("child3"), Tree.new("child4")])])
puts "Visiting a node"
ruby_tree.visit {|node| puts node.node_name}
puts
puts "visiting entire tree"
ruby_tree.visit_all {|node| puts node.node_name}
現在什麼,我試圖做的是要能夠創建樹嵌套的哈希值,而不是。例如,對於這一個,這將是:
{'grandpa'=> {'dad'=> {'child 1'=> {},'child 2'=> {}},'uncle'= > {'child 3'=> {},'child 4'=> {}}}}
任何想法可以幫助嗎?
你實際上並不需要這個三元語句,因爲'Tree#children'的默認值是[]'。 – Frost 2012-01-04 23:05:06
@MartinFrost +1,你是對的! :) – iain 2012-01-05 00:15:35
這對我來說有點太高級了,但似乎感謝您的時間 – 2012-01-05 20:45:22