Skip to content

Instantly share code, notes, and snippets.

@mrc
Created May 9, 2011 12:55
Show Gist options
  • Save mrc/962465 to your computer and use it in GitHub Desktop.
Save mrc/962465 to your computer and use it in GitHub Desktop.
ruby tree ("seven languages")
class Tree
attr_accessor :children, :name
def initialize(tree, name='root')
@name = name
@children = tree.map do |k,v|
Tree.new(v, k)
end
end
def visit_all(depth=0, &block)
visit(depth, &block)
children.each {|c| c.visit_all(depth+1, &block)}
end
def visit(depth=0, &block)
block.call(self, depth)
end
end
t = Tree.new({
"Honor" => {
"America" => {
"Weapons" => {},
"Wood working" => {
"Haircuts" => {},
"Greatness Itself" => {}}},
"Buffets" => {
"Teamwork" => {},
"Selfishness" => {}}}})
t.visit_all do |node, depth|
indent = ' ' * depth
puts indent + node.name
end
@mrc
Copy link
Author

mrc commented May 9, 2011

The exercise was to extend the Tree class so you could pass a hash to the initialiser.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment