nbonbon
nbonbon

Reputation: 1767

concatAll on a Ruby tree

I have two classes Leaf & BinaryNode Leaf contains one field that is a string BinaryNode contains two children of which both are either a Leaf or a BinaryNode

I am trying to write a concatAll method that will return a string of all the words in the tree from left to right...

The following is what I have so far, but it is only returning the last string it finds not the whole string that has been built... how come?

def concatAll
 final = ""

 if @lchild.respond_to?('string')   
   final += @lchild.to_s
 else
   @lchild.concatAll unless @lchild.nil?
 end

 if @rchild.respond_to?('string')   
   final +=  @rchild.to_s
 else
   @rchild.concatAll unless @rchild.nil?
 end
end

Upvotes: 0

Views: 117

Answers (2)

nbonbon
nbonbon

Reputation: 1767

I figured it out I needed final += in front of the recursive call for when it comes back up the tree.

def concatAll
 final = ""

 if @lchild.respond_to?('string')   
    final += @lchild.to_s
 else
   final += @lchild.concatAll unless @lchild.nil?
 end

 if @rchild.respond_to?('string')   
   final +=  @rchild.to_s
 else
   final += @rchild.concatAll unless @rchild.nil?
 end

 final
end

Special thanks to Mark Thomas

Upvotes: 1

Mark Thomas
Mark Thomas

Reputation: 37517

The return value of a method is the value of the last expression executed. Without an explicit return value, you're just getting the last string found.

You can simply add one line before the end:

  final
end

and that would return the value of final.

Upvotes: 1

Related Questions