I initialized a tree using a nested hash as input, but when I recursively call Tree.new
on the children, it doesn't seem to pass each child as a hash. As a pretty ugly, but working, alternative, I translated everything to arrays.
Is there a way to preserve the hash?
I'm doing this exercise using Ruby 1.9.3, so I can't use Ruby 2.0.0's to_h
method.
class Tree
attr_accessor :node_name, :children
def initialize(arr)
arr = arr.to_a unless arr.is_a?(Array)
arr.flatten!
@node_name = arr.first
@children = []
arr.last.each { |c| @children << Tree.new(c) }
end
def visit(&block)
block.call self
end
def visit_all(&block)
visit &block
children.each { |c| c.visit_all(&block) }
end
end
family_tree = Tree.new({'grandpa' => { 'dad' => { 'child 1' => {}, 'child 2' => {} },
'uncle' => {'child 3' => {}, 'child 4' => {} } } })
family_tree.visit_all { |node| p node.node_name }