From: "David A. Black" Date: 2009-04-30T00:43:33+09:00 Subject: Re: Why does attr_accessor in module require 'self.'? Hi -- Brian Hartin wrote: > The second and third posts have made it clear for me. This is necessary > to allow local variables with the same name as instance variables. A > contrasting example from a statically typed language makes this more > clear (for me): > > (Java) > > public class Foo > private int x; > > public void bar() { > int x = 2; // Very obviously a local variable > } > end > > Since Ruby variables are allocated on first use, and Ruby has no > explicit variable declaration syntax, there would be no way to have a > local variable 'x' if an instance variable '@x' existed: > > class Foo > attr_accessor :x > > def bar > # If this were the same as self.x = 2, or @x = 2, > # it would not be possible to have a local variable 'x'? > x = 2 > end > end Remember, though, that @x = 2 and obj.x = 2 # where obj may or may not be self have nothing to do with each other. As Florian said, obj.x = 2 is a method call (the method being x=). David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Now out in PDF: The Well-Grounded Rubyist (http://manning.com/black2) "Ruby 1.9: What You Need To Know" Envycasts with David A. Black http://www.envycasts.com