#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2011
    Posts
    1
    Rep Power
    0

    Ruby - Recursive stack level too deep


    Hi there,

    I'm trying to run the following script:
    PHP Code:
    class Node
      
      data 
    nil
      children 
    nil
      
      attr_accessor 
    :children, :data
        
      def initialize
    (datachildren=Array.new)
        
    self.data data
        self
    .children children
      end
      
      def addchild
    (child)
        
    self.children << child
      end
      
      def printtree
    ()
        print 
    self.data.url"\n"
        
    self.children.each{ |child
          print 
    child.printtree()
          }
      
    end  
    end 
    But the method printtree is running till the stack level is too deep.... this is strange because it should not. So i'm sure I made a type in my ruby script. But i'm pretty new to ruby so obviously i don't see it haha.

    Hope you can help me. That would be a blast!

    Thanks,
    Giac0m0
  2. #2
  3. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Mar 2004
    Location
    Central Washington (USA)
    Posts
    518
    Rep Power
    11
    This runs fine for me, printing the parent nodes data first and then the children. Maybe you're passing the children incorrectly to Node.new()?

    Code:
    class Node 
       
      #data = nil 
      #children = nil 
       
      attr_accessor :children, :data 
         
      def initialize(data, children=Array.new) 
        self.data = data 
        self.children = children
      end 
       
      def addchild(child) 
        self.children << child 
      end 
       
      def printtree() 
        print self.data, "\n" 
        self.children.each{ |child|  
          print child.printtree() 
          } 
      end   
    end
    
    n1 = Node.new('n1')
    n2 = Node.new('n2')
    n3 = Node.new('n3', [n2, n1])
    
    #n2.printtree
    n3.printtree

IMN logo majestic logo spyfu logo threadwatch logo seochat tools logo