/ Published in: Ruby
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
class Tree attr_reader :value def initialize(value) @value = value @children = [] end def <<(value) subtree = Tree.new(value) @children << subtree return subtree end end # Here�s code to create a specificTree(Figure 7-1): t = Tree.new("Parent") child1 = t << "Child 1" child1 << "Grandchild 1.1" child1 << "Grandchild 1.2" child2 = t << "Child 2" child2 << "Grandchild 2.1" class Tree def each yield value @children.each do |child_node| child_node.each { |e| yield e } end end end # The each method traverses the tree in a way that looks right: t.each { |x| puts x }
URL: http://www.devarticles.com/c/a/Ruby-on-Rails/Iterators-in-Ruby/1/