0

In the code below, starting_node isn't being interpreted as a setter method if I omit self; it becomes a local variable.

class Stack
  attr_accessor :starting_node
  def push(node)
    ...
    self.starting_node = node
    ...
  end
end

Why is the explicit self needed when it works implicitly elsewhere?

How does variable assignment work if this:

local_variable.=("some string")

is invalid, that is what is it if not a method?

sawa
  • 165,429
  • 45
  • 277
  • 381
tsiege
  • 468
  • 1
  • 4
  • 17
  • 1
    Isn't this just another `p = 6` vs `self.p = 6` issue? `starting_node.head = node` is really `self.starting_node.head=(node)` (the extra `.` turns `starting_node` into a call to the accessor method). – mu is too short May 03 '14 at 16:57
  • Obviously, `=` cannot be a method because a method is called on an object, whereas the purpose of `=` is to assign something to a local variable with that name that had not previously existed. – sawa May 03 '14 at 17:24

1 Answers1

1

Because otherwise it would be impossible to set local variables at all inside of methods. For example:

class ExampleClass
  attr_reader :last_set
  def method_missing(name, *args)
    if name.to_s =~ /=$/
      @last_set = args.first
    else
      super
    end
  end

  def some_method
    some_variable = 5 # Set a local variable? Or call method_missing?
    puts some_variable
  end
end
Ajedi32
  • 45,670
  • 22
  • 127
  • 172