From: Adam Shelly Date: 2008-06-13T05:45:01+09:00 Subject: Re: Trie data structure On 6/12/08, Justin To wrote: There are a couple of issues with this code, here are some hints. > # 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' 'empty' is not nil - it will act like a true, which is the opposite of what the comments say this function should do. > 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 this code is only testing the value of the first child: it has a return statement in both branches of the 'if', so it will exit after the first test. > 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) you can use the 'private' keyword here, which enforces 'do not call outside of class'. > 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 > as your comments say, If the digit already exists in the children, add_digit will return nil. In that case, you will set current_node to nil here. You probably want to set it to something else. > end > > # End of class Trie > end > hope this helps, -Adam