I am implementing BST in ruby and writing insert method using recursion.
I am trying to use attr_accessor for setting and getting root but it doesn't work. Can anyone help out?
class Node
attr_accessor :value, :left_child, :right_child
def initialize (value)
@value = value
@left_child = nil
@right_child = nil
end
end
class BST
attr_accessor :root
def initialize
@root = nil
end
def insert(value, node)
if node == nil
node = Node.new(value)
return node
end
return node if node.value == value
if node.value > value
if node.left_child == nil
node.left_child = Node.new(value)
return
else
insert(value, node.left_child)
end
else
if node.right_child == nil
node.right_child = Node.new(value)
return
else
insert(value, node.right_child)
end
end
end
end
mybst = BST.new
p mybst.root
mybst.insert(1, mybst.root)
mybst.insert(2, mybst.root)
mybst.insert(10, mybst.root)
mybst.insert(12, mybst.root)
p mybst
The code above shows a simple implementation of Node class and a BST class with insert method. Gives me #<BST:0x00557398d02378 @root=nil>
If I use a self.root it works.
One can use @root to access the root but a class should not interact with its instance variables directly. That's why we need a getter and setter method provided by attr_accessor. But it's not working. What I am missing ?
Below are the screenshots of the book POODR. It says never to use instance variables directly even in class.
nil
andfalse
so unless there's some way that things likeright_child
can ever be literallyfalse
it's not necessary nor recommended to do comparisons like== nil
. This not only clutters your code up and raises questions about what values that property can contain, but runs the risk of an accidental assignment if you type= nil
by mistake. – tadman