From: 7stud -- Date: 2009-04-29T08:34:42+09:00 Subject: Re: Why does attr_accessor in module require 'self.'? 7stud -- wrote: > class B > def a > @a > end > > def a=(val) > @a = val > end > > def bar > a = "bar" #<----**** > end > > def baz > self.a = "baz" > end > > def foo > a = 10 > end > end > > b = B.new > puts b.bar > puts b.a > puts b.baz > puts b.a > > > --output:-- > bar > nil > baz > baz > > > All of which I guess has nothing to do with the op's question. The op > correctly identified that self.a = "baz" calls the a= method, but that a > = "bar" does not. I guess I would pose this question to the op: when > have you ever been able to access the a= method in a class without using > the format some_obj.a = ? I guess the idea here: > def bar > a = "bar" #<----**** > end > > def baz > self.a = "baz" > end is that when you call a method without a receiver, self is implied. So the bar method would be equivalent to: > def bar > self. a = "bar" #<----**** > end > Therefore bar and baz have the same format and should do the same thing. But... John Barnette wrote: > Ruby automatically creates local variables upon > assignment. which might be explained further(though perhaps wrongly) by saying: before ruby can attach 'self.' to the front of 'a' in the bar method: > def bar > a = "bar" > end the parser tells ruby that it should create a local variable called 'a' instead and assign it the value on the right of the equals sign. As a result unadorned names, for example 'a' vs. 'obj.a', that appear to the left of an equals sign cause ruby to create a local variable and assign the local variable the value to the right of the equals sign. -- Posted via http://www.ruby-forum.com/.