From: Jacob Fugal Date: 2004-11-12T04:39:20+09:00 Subject: Re: automatically call function on attribute set On Fri, 12 Nov 2004 04:13:30 +0900, Joe Van Dyk wrote: > > What is the difference between self.x and @x? self.x, sends either the :x or :x= method to self, depending if it's an lvalue or rvalue respectively. @x just reads/writes to the instance variable directly. If you're just using attr_accessor :x, they're the same thing, but if you have, for instance: class Foo def bar raise "@bar and @baz out of sync" unless @bar == @baz @bar end def bar=( new_bar ) puts "setting @bar and @baz" @bar = @baz = new_bar end def test1 self.bar = "test1" end def test2 @bar = "test2" end end foo = Foo.new foo.bar = "test" # => setting @bar and @baz puts foo.bar # => test foo.test1 # => setting @bar and @baz puts foo.bar # => test1 foo.test2 puts foo.bar # RuntimeError: @bar and @baz out of sync Using self.bar= keeps @bar and @baz in sync, while setting @bar directly doesn't update @baz. Generally, if you have non-trivial accessors for instance variables, you should use them even inside the object rather than accessing the instance variables directly. I usually use them even if the accessor is trivial, so that if the accessor becomes non-trivial later I don't have to go find and fix all the places where the instance variables are currently accessed directly. Jacob Fugal