RE: not understanding return statement

Andy Jones <[email protected]>
Newsgroups gmane.comp.lang.ruby.general
Message-ID <[email protected]>
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 same thing.

I suspect you need to go back and learn some more about classes and attributes – sorry.

From: ruby-talk [mailto:[email protected]] On Behalf Of Igor Maljkovic
Sent: 12 December 2018 10:08
To: [email protected]
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 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


Click here to view Company Information and Confidentiality Notice.<http://www.jameshall.co.uk/index.php/small-print/email-disclaimer>

Please note that we have updated our privacy policy in line with new data protection regulations. Please refer to our website to view the ways in which we handle your data.


Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.