I wrote the binary search tree code with Ruby. I'm now wondering why this code needs self
in self.left = Node.new(3)
to make a new node.
I was thinking that self can be removed like this left = Node.new(3)
because in this case receiver is obvious(an instance to which insert_left method applied). But it seems wrong.. Can you please help me why my thought is wrong.
module BinaryTree
class Node
attr_accessor :value, :left, :right
def initialize(value)
@value = value
end
def insert(v)
case @value <=> v
when 1 then insert_left(v)
when -1 then insert_right(v)
when 0 then nil
end
end
private
def insert_left(v)
if left
left.insert(v)
else
self.left = Node.new(v)
end
end
def insert_right(v)
if right
right.insert(v)
else
self.right = Node.new(v)
end
end
end
end