In your method #insert, root is just a variable. Putting `root` as the
last statement in #insert will return the value of that variable *from
the #insert method*.
But it won’t set the @root attribute on the class, which is what you are
reading when you say `p x.root`. @root is an attribute on the class
BinarySearchTree; root is a variable in the insert method. They are not the
I suspect you need to go back and learn some more about classes and
attributes – sorry.
*From:* ruby-talk [mailto:email@example.com] *On Behalf Of *Igor
*Sent:* 12 December 2018 10:08
*Subject:* not understanding return statement
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
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:
attr_accessor :value, :left_child, :right_child
@value = value
@left_child = nil
@right_child = nil
@root = nil
def insert(*root* = @root, *value*)
if root == nil
root = *Node*.new(value)
elsif value <= root.value
root.left_child = insert(root.left_child, value)
root.right_child = insert(root.right_child, value)
@root = root #works with this return statement
#root <- doesn't work with this statement, why!!!
x = *BinarySearchTree*.new()
Click here to view Company Information and Confidentiality Notice.
protection regulations. Please refer to our website to view the ways in
which we handle your data.