From: frank Date: 2006-02-14T03:13:25+09:00 Subject: Re: tree structures Okay, so I need to approach this head on from an OO standpoint. I have Ruby Way and Programming Ruby. With the program I have written so far, I parsed the tree information into a set of linked lists (see below). I realize this may not be the best way to begin this program. I need to embrace classes and represent the tree as an object. I am looking over the example in the Ruby Way on binary trees. I get what is going on with Hal Fultons examples. But it seems like there is a huge gulf between my procedural thinking and an OO thinking with regard to this tree structure. How would you represent a linked list in Ruby? In other words, would it be possible to convert the following procedural Ruby code into OO ruby so that I would be able to "get it". Or are there equivalent examples procedural to OO. I mean, what I have written is awful looking compared to the class Node you posted earlier...and while I understand the ideas of instance variables and self and classes methods etc. I am struggling to get them right in my head. -frank This is not the full program but enough to see what I am trying to accomplish. #!/usr/bin/ruby -w class Integer def odd? self % 2 == 0 end end #class Integer # def even?() self.[](0) == 0 end # def odd?() self.[](0) == 1 end #end tree = "(((aa:0.490,bb:0.50):0.70,cc:0.85):0.90,(ee:0.95,dd:0.99):0.100);" print "here is the tree", tree, "\n" tree_array = tree.scan(/[a-z]+|\d+\.\d+|[(,);]/) tree_array_size = tree_array.size # want to use this but need to parse the tree file better #initializing an array for a linked list so that I can begin traversing nodes leaf = Array.new node = Array.new left = Array.new right = Array.new ancestor = Array.new branch = Array.new m = 0 # a counter used for assigning numbers to nodes i = 0 #counter for reading through all the elements of a newick tree while i < tree_array_size if tree_array[i] == '(' && i == 0 print "ROOT", "\n" i += 1 m += 1 left_m = m*2 right_m = m*2+1 node[m] =[] left[left_m] = [] right[right_m] = [] elsif tree_array[i] == '(' && i != 0 print " UP_PASS", "\n" i += 1 m = m*2 if node[m] == nil left_m = m*2 right_m = m*2+1 node[m] = [] left[left_m] = [] right[right_m] = [] ancestor[m] == node[m/2] print "node is ", m, "\n" print "left ", left_m, "\n" print "right ", right_m, "\n" if m.odd? != true print "ancestor odd is ", (m-1)/2, "\n" else print "ancestor is ", m/2, "\n" end elsif node[m] != nil m = m/2 print "node already defined looking RIGHT on the tree", "\n" m = m*2+1 left_m = m*2 right_m = m*2+1 node[m] = [] left[left_m] = [] right[right_m] = [] ancestor[m] == node[m/2] print "node is ", m, "\n" print "left ", left_m, "\n" print "right ", right_m, "\n" if m.odd? != true print "ancestor odd is ", (m-1)/2, "\n" else print "ancestor is ", m/2, "\n" end else print "NO doesn't work", "\n" end .......