<p>Ruby setters—whether created by <code>(c)attr_accessor</code> or manually—seem to be the only methods that need <code>self.</code> qualification when accessed within the class itself.  This seems to put Ruby alone the world of languages:</p>

<ul>
<li>All methods need <code>self</code>/<code>this</code> (like Perl, and I think Javascript)</li>
<li>No methods require <code>self</code>/<code>this</code> is (C#, Java)</li>
<li>Only setters need <code>self</code>/<code>this</code> (Ruby?)</li>
</ul>

<p>The best comparison is C# vs Ruby, because both languages support accessor methods which work syntactically just like class instance variables: <code>foo.x = y</code>, <code>y = foo.x</code> . C# calls them properties.</p>

<p>Here's a simple example; the same program in Ruby then C#:</p>

<pre><code>class A
  def qwerty; @q; end                   # manual getter
  def qwerty=(value); @q = value; end   # manual setter, but attr_accessor is same 
  def asdf; self.qwerty = 4; end        # "self." is necessary in ruby?
  def xxx; asdf; end                    # we can invoke nonsetters w/o "self."
  def dump; puts "qwerty = #{qwerty}"; end
end

a = A.new
a.xxx
a.dump
</code></pre>

<p>take away the <code>self.qwerty =()</code> and it fails (Ruby 1.8.6 on Linux &amp; OS X).  Now C#:</p>

<pre><code>using System;

public class A {
  public A() {}
  int q;
  public int qwerty {
    get { return q; }
    set { q = value; }
  }
  public void asdf() { qwerty = 4; } // C# setters work w/o "this."
  public void xxx()  { asdf(); }     // are just like other methods
  public void dump() { Console.WriteLine("qwerty = {0}", qwerty); }
}

public class Test {
  public static void Main() {
    A a = new A();
    a.xxx();
    a.dump();
  }
}
</code></pre>

<p>Question: Is this true?  Are there other occasions besides setters where self is necessary? I.e., are there other occasions where a Ruby method <em>cannot</em> be invoked <em>without</em> self?</p>

<p>There are certainly lots of cases where self <em>becomes</em> necessary.  This is not unique to Ruby, just to be clear:</p>

<pre><code>using System;

public class A {
  public A() {}
  public int test { get { return 4; }}
  public int useVariable() {
    int test = 5;
    return test;
  }
  public int useMethod() {
    int test = 5;
    return this.test;
  }
}

public class Test {
  public static void Main() {
    A a = new A();
    Console.WriteLine("{0}", a.useVariable()); // prints 5
    Console.WriteLine("{0}", a.useMethod());   // prints 4
  }
}
</code></pre>

<p>Same ambiguity is resolved in same way.  But while subtle I'm asking about the case where </p>

<ul>
<li>A method <em>has</em> been defined, and</li>
<li><em>No</em> local variable has been defined, and</li>
</ul>

<p>we encounter</p>

<pre><code>qwerty = 4
</code></pre>

<p>which is ambiguous—is this a method invocation or an new local variable assignment?</p>

<hr>

<p>@Mike Stone</p>

<p>Hi!  I understand and appreciate the points you've made and your 
example was great.  Believe me when I say, if I had enough reputation,
I'd vote up your response.  Yet we still disagree: </p>

<ul>
<li>on a matter of semantics, and</li>
<li>on a central point of fact</li>
</ul>

<p>First I claim, not without irony, we're having a semantic debate about the 
meaning of 'ambiguity'.</p>

<p>When it comes to parsing and programming language semantics (the subject 
of this question), surely you would admit a broad spectrum of the notion 
'ambiguity'.  Let's just adopt some random notation: </p>

<ol>
<li>ambiguous: lexical ambiguity (lex must 'look ahead')</li>
<li>Ambiguous: grammatical ambiguity (yacc must defer to parse-tree analysis)</li>
<li>AMBIGUOUS: ambiguity knowing everything at the moment of execution</li>
</ol>

<p>(and there's junk between 2-3 too).  All these categories are resolved by 
gathering more contextual info, looking more and more globally.  So when you 
say,</p>

<blockquote>
  <p>"qwerty = 4" is UNAMBIGUOUS in C#
  when there is no variable defined...</p>
</blockquote>

<p>I couldn't agree more.  But by the same token, I'm saying </p>

<blockquote>
  <p>"qwerty = 4" is un-Ambiguous in ruby
  (as it now exists)</p>
  
  <p>"qwerty = 4" is Ambiguous in C#</p>
</blockquote>

<p>And we're not yet contradicting each other.  Finally, here's where we really 
disagree: Either ruby could or could not be implemented without any further 
language constructs such that,</p>

<blockquote>
  <p>For "qwerty = 4," ruby UNAMBIGUOUSLY
  invokes an existing setter if there<br>
  is no local variable defined</p>
</blockquote>

<p>You say no.  I say yes; another ruby could exist which behaves exactly like 
the current in every respect, <em>except</em> "qwerty = 4" defines a new 
variable when no setter and no local exists, it invokes the setter if one 
exists, and it assigns to the local if one exists.  I fully accept that I 
could be wrong.  In fact, a reason why I might be wrong would be interesting.</p>

<p>Let me explain.</p>

<p>Imagine you are writing a new OO language with accessor methods looking
like instances vars (like ruby &amp; C#).  You'd probably start with 
conceptual grammars something like:</p>

<pre><code>  var = expr    // assignment
  method = expr // setter method invocation
</code></pre>

<p>But the parser-compiler (not even the runtime) will puke, because even after
all the input is grokked there's no way to know which grammar is pertinent.
You're faced which a classic choice.  I can't be sure of the details, but
basically ruby does this:</p>

<pre><code>  var = expr    // assignment (new or existing)
  // method = expr, disallow setter method invocation without .
</code></pre>

<p>that is why it's un-Ambiguous, while and C# does this:</p>

<pre><code>  symbol = expr // push 'symbol=' onto parse tree and decide later
                // if local variable is def'd somewhere in scope: assignment
                // else if a setter is def'd in scope: invocation
</code></pre>

<p>For C#, 'later' is still at compile time.</p>

<p>I'm sure ruby could do the same, but 'later' would have to be at runtime, because 
as ben points out you don't know until the statement is executed which case 
applies.</p>

<p>My question was never intended to mean "do I really need the 'self.'?" or "what 
potential ambiguity is being avoided?"  Rather I wanted to know why was this
particular choice made?  Maybe it's not performance.  Maybe it just got the job
done, or it was considered best to always allow a 1-liner local to override a 
method (a pretty rare case requirement) ...</p>

<p>But I'm sort of suggesting that the most dynamical language might be the one which
postpones this decision the longest, and chooses semantics based on the most contextual 
info: so if you have no local and you defined a setter, it would use the setter.  Isn't 
this why we like ruby, smalltalk, objc, because method invocation is decided at runtime,
offering maximum expressiveness?</p>

[{'answer_id': 44779, 'author': 'Mike Stone', 'author_id': 122, 'author_profile': 'https://Stackoverflow.com/users/122', 'pm_score': 6, 'selected': False, 'text': '<p>Well, I think the reason this is the case is because <code>qwerty = 4</code> is ambiguous—are you defining a new variable called <code>qwerty</code> or calling the setter?  Ruby resolves this ambiguity by saying it will create a new variable, thus the <code>self.</code> is required.</p>\n\n<p>Here is another case where you need <code>self.</code>:</p>\n\n<pre><code>class A\n  def test\n    4\n  end\n  def use_variable\n    test = 5\n    test\n  end\n  def use_method\n    test = 5\n    self.test\n  end\nend\na = A.new\na.use_variable # returns 5\na.use_method   # returns 4\n</code></pre>\n\n<p>As you can see, the access to <code>test</code> is ambiguous, so the <code>self.</code> is required.</p>\n\n<p>Also, this is why the C# example is actually not a good comparison, because you define variables in a way that is unambiguous from using the setter. If you had defined a variable in C# that was the same name as the accessor, you would need to qualify calls to the accessor with <code>this.</code>, just like the Ruby case.</p>\n'}, {'answer_id': 44835, 'author': 'ben', 'author_id': 4607, 'author_profile': 'https://Stackoverflow.com/users/4607', 'pm_score': 5, 'selected': True, 'text': '<p>The important thing to remember here is that Ruby methods can be (un)defined at any point, so to intelligently resolve the ambiguity, every assignment would need to run code to check whether there is a method with the assigned-to name at the time of assignment.</p>\n'}, {'answer_id': 23448046, 'author': 'Ajedi32', 'author_id': 1157054, 'author_profile': 'https://Stackoverflow.com/users/1157054', 'pm_score': 4, 'selected': False, 'text': '<p>Because otherwise it would be impossible to set local variables at all inside of methods. <code>variable = some_value</code> is ambiguous. For example:</p>\n\n<pre><code>class ExampleClass\n  attr_reader :last_set\n  def method_missing(name, *args)\n    if name.to_s =~ /=$/\n      @last_set = args.first\n    else\n      super\n    end\n  end\n\n  def some_method\n    some_variable = 5 # Set a local variable? Or call method_missing?\n    puts some_variable\n  end\nend\n</code></pre>\n\n<p>If <code>self</code> wasn\'t required for setters, <code>some_method</code> would raise <code>NameError: undefined local variable or method \'some_variable\'</code>. As-is though, the method works as intended:</p>\n\n<pre><code>example = ExampleClass.new\nexample.blah = \'Some text\'\nexample.last_set #=&gt; "Some text"\nexample.some_method # prints "5"\nexample.last_set #=&gt; "Some text"\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/44715', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4615/']