From: "Jesús Gabriel y Galán" Date: 2011-10-05T00:51:03+09:00 Subject: Re: Local vs method vs instance (was: Operator Overloading) On Tue, Oct 4, 2011 at 5:31 PM, Darryl L. Pierce wrote: > On 10/04/2011 11:11 AM, Adam Prescott wrote: >>>> (Of course, 'x' and 'self.x' are the same; you can write 'self.x' if you >>>> think it's clearer) >>> >>> I don't think so. 'x' is a local variable, while '@x' is an instance >>> variable. And since the fields are instance variables they have to be >>> prefixed with '@'. >>> >> >> Not quite. :) >> >> class Foo >>   attr_reader :x >> >>   def initialize(x) >>     @x = x >>   end >> >>   def bar >>     x # :) >>   end >> end >> >> f = Foo.new(1) >> puts f.bar >> >> http://ideone.com/mbPc0 >> >> If there's no local variable in the scope, the interpreter sees it as a >> method call. If it's ambiguous, it'll pick the variable over the method >> call, unless you force it with a trailing (). >> >> x = 1 >> def x; 2; end >> puts x >> puts x() > > Okay, then this flies in the face of how I understood variables. I would > have thought the act of having 'x' in the definition for bar in the > above created a local variable in the current scope. Only an assignment creates a local variable in the scope. def bar x = 2 end This creates a local variable x in the method bar. If there are no assignments, the parser understands that references to x must be method calls. This is due to the syntax ambiguity between methods and local variables, because ruby allows you to call methods without parens. So, to break the ambiguity, the parser marks references as methods by default, and only as local variables when it sees an assignment. Jesus.