not understanding return statement
Igor Maljkovic <[email protected]>
| Newsgroups | gmane.comp.lang.ruby.general |
|---|---|
| Message-ID | <CABU5DAG1c9t0LkNoa6aZFeYyK0x-pfrKB=C4YKmYXOttas4PKg@mail.gmail.com> |
Hi all, I need help understanding part of my code. I'm learning about data structures, at the moment binary search tree. This code does what I want, but I don't understand return statement in insert method. Why @root = root works as it works. If i put last line just root, global variable root is nil instead of tree filled with nodes. Here is my code: class BinarySearchTree class Node attr_accessor :value, :left_child, :right_child def initialize(value) @value = value @left_child = nil @right_child = nil end end attr_accessor :root def initialize() @root = nil end def insert(root = @root, value) if root == nil root = Node.new(value) elsif value <= root.value root.left_child = insert(root.left_child, value) else root.right_child = insert(root.right_child, value) end @root = root #works with this return statement #root <- doesn't work with this statement, why!!! end end x = BinarySearchTree.new() x.insert(15) x.insert(10) p x.root Unsubscribe: <mailto:[email protected]?subject=unsubscribe> <http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>