From: Jim Cochrane Date: 2006-07-23T06:40:07+09:00 Subject: Re: Self, looking for a good summary explanation On 2006-07-22, Dark Ambient wrote: > Sorry, because I have the books and have / continuing to read, just > trying to wrap myself around one aspect of "self". > > My understanding is that 'self' changes amongst objects depending on > program code execution. This I get (at some level). what I don't > understand is why are some objects named self outright and does it > actually matter if you named something self or something else ? self is not a variable name - It's a key word that refers to the current object (the object to which the currently executing code in question belongs). It's often not needed - e.g.: class A def b # ... end def c self.b end def d b end end both 'c' and 'd' do exactly the same thing, call b on the current object, using different syntax. However, sometimes self is necessary - e.g.: x.rb: class X def method1(some_object) some_object.do_something_or_other(self) # Pass my'self' - me, the # current object as an arg. end # ... end y.rb: require 'x' class Y def do_work x = X.new x.method1(self) # Again, pass my'self'. end def do_something_or_other(client) puts "doing something with #{client}" end end test-y: #!/usr/bin/env ruby require 'y' y = Y.new y.do_work Note that 'self' is used twice in the above example. (This is the only way, as far as I know, to pass a reference to "the current object" in these method calls, so 'self' is a necessary keyword. All OO languages have such a keyword - e.g., 'this' in C++ and Java, 'Current' in Eiffel, 'self' in Python, Ruby, and, I think, Smalltalk.) It doesn't do anything useful, since it's just a demo, but a serious program that uses 'self' will need it to do something useful, of course.