From: 7stud -- Date: 2009-05-03T05:24:49+09:00 Subject: Re: Help me understand 'self' vs current object C. Dagnon wrote: > >Help me understand 'self' vs current object > class A def initialize @x = 10 end def x=(val) @x = val end def x @x end def test1 self.x = 0 end end a = A.new puts a.x a.test1 puts a.x --output:-- 10 0 So far so good. class A def meth puts "hello" end def test2 meth end end a.test2 --output:-- hello Bingo. When ruby sees a method call without an object in front of it, the implied caller is self. Inside the method test2, self is the object that called test2. In this case, the object 'a' called test2, so inside test2 self=a. The call to meth inside test2 has no object in front of it, so the implied caller is self. As a result, calling meth is equivalent to self.meth which is equivalent to a.meth. Now consider this code: class A def test3 x = 0 end end a.x = 10 a.test3 puts a.x What's the output? Applying the previous lessons, 'a' is calling test3, so inside test3 self is 'a'. The method call 'x=' inside test3 does not have an object in front of it, so the method call x= is equivalent to self.x=, which is equivalent to a.x=. Here's the output: --output:-- 10 What the??!! What happened? As the smart guys pointed out in another current thread, when the ruby parser first encounters the line: x = 10 it tags it with the message, "create a variable called x and assign 10 to it". As a result, ruby dutifully follows the parser's instructions rather than slapping 'self' in front of x=. In other words, an unadorned name with = after it causes a local variable to be created rather than calling the 'name=' method. -- Posted via http://www.ruby-forum.com/.