From: "David A. Black" Date: 2009-06-23T01:46:13+09:00 Subject: Re: Some confusion on self and the like.... Hi -- On Tue, 23 Jun 2009, Alexander Trauzzi wrote: > Hello all, > > I'm getting somewhat confused by the use of "self" when doing Ruby > programming. > > Self in other languages has typically referred to a currently executing > class, while "this" is used for the current instance. > > How does it work in Ruby, given that I've seen self used to describe > static methods AND refer to the current instance? At any given point during execution, one object is 'self'. That object can be of any class -- which means it can be a Class object. For example, here: class C self end self evaluates to the class object C, which is itself an instance of Class. Here, however: class C def some_method self end end self evaluates to whatever instance of C is calling some_method. In the first example, you can figure out exactly which object self will be by looking at the code. In the second example, you know that it will be an instance of C but that instance doesn't exist yet. As I've always said: the answer to 75% of all questions about Ruby is "Because classes are objects" :-) > Moreover, how do I get the furthest-down-the-inheritance-chain name of > the currently running instance? I'm not sure what you mean. The class of self? (Which would be self.class.) > Are there any good tutorials with examples on how to do reflection along > these lines in Ruby? There's my new book: http://www.manning.com/black2 :-) David -- David A. Black / Ruby Power and Light, LLC Ruby/Rails consulting & training: http://www.rubypal.com Now available: The Well-Grounded Rubyist (http://manning.com/black2) "Ruby 1.9: What You Need To Know" Envycasts with David A. Black http://www.envycasts.com