Here's the code:
class Something attr_accessor :x def initialize(x) @x = x end def get_x x end end something = Something.new(5) something.get_x # => 5 Why interpreter returns 5 if x is just a local variable in get_x method? Thanks
x is also a method. attr_accessor :x adds x= and x to your class. So, get_x is calling the x method, and returning the value for @x. see http://www.rubyist.net/~slagell/ruby/accessors.html for details.
attr_accessor :x adds two methods for you:
def x=(val) @x = val end def x @x end So you don't actually need get_x getter if you've added attr_accessor method.
UPD
So the question is
class Something attr_accessor :x def initialize(x) @x = x end def set_x=(new) x = new end end Why won't x = new call default x setter: because default x setter is an instance method so you can call it for an object (Something instance) but not in your class like you try.
attr_accessor is just a "helper" it creates two methods for you, but you are free to create as much as you needdef x; "method"; end; p x; x = 42; p x. The first x invokes the method (because no local variable with that name exists), but the second identical x reads the local variable. Local variables mask methods in the same scope unless you prefix with self.