From: "Darryl L. Pierce" Date: 2011-10-05T00:31:39+09:00 Subject: Local vs method vs instance (was: Operator Overloading) 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. -- Darryl L. Pierce http://mcpierce.multiply.com/ "What do you care what people think, Mr. Feynman?"