On Jul 22, 2006, at 11:59 AM, Dark Ambient wrote:
> 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 ?

Objects aren't really 'named' by the variables that reference them.
Consider:

def outer
   a = 3
   puts a	# 3
   inner
   puts a	# 3
end

def inner
   a = 4
   puts a	# 4
end

outer    # call method outer

Both methods have a variable 'a', but the scope is different in each
case so they are in fact different variables existing in two different
scopes but utilizing the same name.  In this case the 'a' in outer
references the Fixnum object 3 and the 'a' in inner references a  
different
object, the Fixnum object 4.

The same concept applies to 'self'. Ruby arranges for the identifier
'self' to reference different objects depending on the scope in which
execution is occurring.  So consider:

class A
   def instance_method_of_A
     self.object_id
   end
end

a1 = A.new
a2 = A.new

a1.instance_method_of_A		# => 1656984
a2.instance_method_of_A		# => 1650774

You can see from this example that 'self' within an instance method
references the object that is receiving the message.  In the first
case the object referenced as a1 is the receiver and self.object_id
returns the object id of that object but in the second case a2 is
the receiver and self.object_id returns a different object id.

The rules regarding scopes, and the object associated with 'self' in
those various scopes, are part of what makes Ruby, well, Ruby. So  
understanding the various scopes and their associated variables is
the key to understanding Ruby code.


Gary Wright