Return to Snippet

Revision: 31179
at August 31, 2010 18:29 by rkumar


Updated Code
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 }

Revision: 31178
at August 31, 2010 18:05 by rkumar


Initial Code
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"

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

Initial Description


Initial Title
ruby tree structure

Initial Tags
ruby

Initial Language
Ruby