Created
October 19, 2013 21:05
-
-
Save jbuda/7061547 to your computer and use it in GitHub Desktop.
Ruby - Day 2 - Seven Languages in Seven Weeks
This file contains 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
# update the tree initialiser to accept a nested structure with hashes and arrays | |
class Tree | |
attr_accessor :children, :node_name | |
def initialize(tree) | |
@node_name = tree.keys()[0] | |
@children = [] | |
tree[tree.keys()[0]].each do |k,v| | |
@children.push(Tree.new({k=>v})) | |
end | |
end | |
def visit_all(&block) | |
visit &block | |
children.each { |c| c.visit_all &block } | |
end | |
def visit(&block) | |
block.call self | |
end | |
end | |
tree = Tree.new({'grandpa'=>{'dad'=>{'child 1'=>{},'child 2'=>{}},'uncle'=>{'child 3'=>{},'child 4'=>{}}}}) | |
tree.visit_all {|node| puts node.node_name } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment