From: Justin To Date: 2008-06-13T02:06:05+09:00 Subject: Re: Trie data structure class Trie attr_reader :value, :children def initialize(value=nil) @value = value # The corresponding value @children = [] # Store hashes inside of the hash end def <<(value) sub_trie = Trie.new(value) @children << sub_trie return sub_trie # End of def <<(value) end # Return true if value exists or nil if value D.N.E. def child_value?(value) if @children.empty? # If @children is empty, then there are no children return 'empty' else # If one of the children contains the value then return true @children.each do |child| if(child.value==value) return true else return nil end end end # End of def child_value?(value) end # Return the child that added the value if the value D.N.E. else return nil, the value already exists # DO NOT ALTER OR CALL OUTSIDE OF CLASS--belongs to def add_number(value) def add_digit(digit) if(!child_value?(digit)) child = self<<(digit) puts "#{digit} added" return child else puts "#{digit}: already exists in the child." return nil end end def add_number(number) current_node = self number.to_s.each_byte do |byte| puts "add_number #{byte.chr.to_i}" puts "Nodeclass: " + current_node.class.to_s current_node = current_node.add_digit(byte.chr.to_i) end end # End of class Trie end t = Trie.new t << 3 t.add_number(234) Output: HashTrie3.rb:50:in `add_number': undefined method `add_digit' for nil:NilClass (NoMethodError) from HashTrie3.rb:47:in `each_byte' from HashTrie3.rb:47:in `add_number' from HashTrie3.rb:62 add_number 2 Nodeclass: Trie 2 added add_number 3 Nodeclass: Trie 3: already exists in the child. # ? add_number 4 # ? Nodeclass: NilClass # ? Somewhere I'm not saving the current node correctly so when it adds 3, it's adding it into the same array that the first 3 (t<<3) and the 2 [t.add_number(234)] is in. But then again, I could have messed up somewhere else. Maybe I'm passing around copies of the current node and not the ACTUAL one. Any help is much appreciated!!!!!!!!!!!!!!!!!!!! Justin -- Posted via http://www.ruby-forum.com/.