I wrote the binary search tree code with Ruby. I'm now wondering why this code needs
self.left = Node.new(3)
left = Node.new(3)
attr_accessor :value, :left, :right
@value = value
case @value <=> v
when 1 then insert_left(v)
when -1 then insert_right(v)
when 0 then nil
self.left = Node.new(v)
self.right = Node.new(v)
left = x that's interpreted as a variable assignment. Calling
self.left = x is a method call of
self. These are obviously two different things but unless you're familiar with the notation this might not make any sense. It isn't especially intuitive and is rather perplexing for beginners, especially when
x = left works fine without having to be explicit about
left being a variable or a method call.
Unlike some languages that have prefixes on local variables (Perl, PHP, etc.) there's no such identifier in Ruby. As such it interprets things of the form
lvalue = expr to be variable assignments and
object.property = expo to be method calls to a mutator method.
Ruby does identify instance and class level variables like
@x = expr and
@@y = expr but that's a different thing altogether.