0

I have the following code, and was wondering if someone can tell me why, after running it, the value of @left_child and @right_child are still nil.

I think I know why, but I am asking for confirmation to the community. Also, is there a way I can make this work in a way like this?

 module BinaryTree
    class Node
        attr_accessor :left_child, :right_child

        def initialize(value)
            @value = value
            @left_child = nil
            @right_child = nil
        end

        def add_child(value)
            if value > @value
                create_child(value, @right_child)
            else
                create_child(value, @left_child)
            end
        end

        private

        def create_child(value, which_child)
            if which_child.nil?
                which_child = Node.new(value)
            else
                which_child.add_child(value)
            end
        end
    end
end

node = BinaryTree::Node.new(50)

node.add_child(20)
node.left_child # => nil

node.add_child(70)
node.right_child # => nil
the Tin Man
  • 158,662
  • 42
  • 215
  • 303

2 Answers2

0

They are still nil because you've never assign values to them. Instead, you should change to this:

module BinaryTree
  class Node
    attr_accessor :left_child, :right_child

    def initialize(value)
      @value = value
      @left_child = nil
      @right_child = nil
    end

    def add_child(value)
      if value > @value
        @right_child = create_child(value, @right_child)
      else
        @left_child = create_child(value, @left_child)
      end
    end

    private

    def create_child(value, which_child)
      if which_child.nil?
        which_child = Node.new(value)
      else
        which_child.add_child(value)
      end
      which_child
    end
  end
end
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Blue Smith
  • 8,580
  • 2
  • 28
  • 33
0

which_child is a variable local to create_child. The value of @right_child is being copied to it when you call the method. Your code is basically the same as

right_child = nil
which_child = right_child
which_child = true
# right_child is still nil!

Variables in Ruby store pointers to objects, and Ruby passes around those pointers by value. See also:

Community
  • 1
  • 1
Max
  • 21,123
  • 5
  • 49
  • 71