Why do Ruby setters need “self.” qualification within the class?

Because otherwise it would be impossible to set local variables at all inside of methods. variable = some_value is ambiguous. 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

If self wasn’t required for setters, some_method would raise NameError: undefined local variable or method 'some_variable'. As-is though, the method works as intended:

example = ExampleClass.new
example.blah="Some text"
example.last_set #=> "Some text"
example.some_method # prints "5"
example.last_set #=> "Some text"

Leave a Comment