Posted By

rkumar on 08/31/10


Tagged

ruby


Versions (?)

ruby tree structure


 / Published in: Ruby
 

URL: http://www.devarticles.com/c/a/Ruby-on-Rails/Iterators-in-Ruby/1/

  1. class Tree
  2. attr_reader :value
  3. def initialize(value)
  4. @value = value
  5. @children = []
  6. end
  7.  
  8. def <<(value)
  9. subtree = Tree.new(value)
  10. @children << subtree
  11. return subtree
  12. end
  13. end
  14.  
  15. # Here�s code to create a specificTree(Figure 7-1):
  16.  
  17. t = Tree.new("Parent")
  18. child1 = t << "Child 1"
  19. child1 << "Grandchild 1.1"
  20. child1 << "Grandchild 1.2"
  21. child2 = t << "Child 2"
  22. child2 << "Grandchild 2.1"
  23.  
  24. class Tree
  25. def each
  26. yield value
  27. @children.each do |child_node|
  28. child_node.each { |e| yield e }
  29. end
  30. end
  31. end
  32.  
  33. # The each method traverses the tree in a way that looks right:
  34.  
  35. t.each { |x| puts x }

Report this snippet  

You need to login to post a comment.