ruby - Why are none of my node children getting set? -
i have next code, , wondering if can tell me why, after running it, value of @left_child
, @right_child
still nil.
i think know why, asking confirmation community. also, there way can create work in way 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
which_child
variable local create_child
. value of @right_child
beingness copied when phone call method. code same as
right_child = nil which_child = right_child which_child = true # right_child still nil!
variables in ruby store pointers objects, , ruby passes around pointers value. see also:
ruby - parameters reference or value? is ruby pass reference or value? ruby
No comments:
Post a Comment