Mercurial > repos > other > SevenLanguagesInSevenWeeks
changeset 21:7e212cc7ec24
Add default Tree code from book's source code
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Sat, 07 Jan 2017 20:36:33 +0000 |
parents | 25c15f27b33d |
children | e020410896ca |
files | 1-Ruby/tree.rb |
diffstat | 1 files changed, 36 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/1-Ruby/tree.rb Sat Jan 07 20:36:33 2017 +0000 @@ -0,0 +1,36 @@ +#--- +# Excerpted from "Seven Languages in Seven Weeks", +# published by The Pragmatic Bookshelf. +# Copyrights apply to this code. It may not be used to create training material, +# courses, books, articles, and the like. Contact us if you are in doubt. +# We make no guarantees that this code is fit for any purpose. +# Visit http://www.pragmaticprogrammer.com/titles/btlang for more book information. +#--- +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( "Ruby", + [Tree.new("Reia"), + Tree.new("MacRuby")] ) + +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}