From: "David A. Black" Date: 2008-09-02T18:22:10+09:00 Subject: Re: Self and Current Class Hi -- On Tue, 2 Sep 2008, Thomas B. wrote: > Pedro Silva wrote: >> I know that Ruby always keeps track of two concepts: self and current >> class. >> >> The programmer only can access the first one, that tracks the current >> object. I know that self is the default receiver when invoking methods >> and that obviously affects the way Ruby processes the code. Fortunately >> self I understand quite well. >> >> My doubt comes with the current class concept. I know that when we use >> instance_eval, self is set to the receiver and current class to the >> singleton class, that's why it allows to define singleton methods. I >> would like to undestand how current class is altered by Ruby because >> there's no way to print stuff and see what happens. >> >> Can anyone enumerate which cases Ruby uses current class and a general >> rule for current class status? >> >> Pedro. > > Hello. > > Well, at first I thought that you can always check the current class > using > class< but now I see I was wrong. Good I realised it before posting. > > In fact, most of the time this is the way to check the current class. I don't think so. Most of the time you're likely to be inside a method definition body, where the singleton class is not relevant unless you invoke it more or less explicitly. > Inside x.instance_eval{} self is set to x, and the current class is set > to class< there, it will become a method of x (you will be able to call it by > x.method, no matter if x is a regular object or a class), and the class > that will hold the method is the x's eigenclass - it will be visible in > class< > But there is an exception from this rule. Inside class declaration: > class K > #here > end > self is set to the class (that is, K), class< the class'es eigenclass, but if you def a method now, it will not become > the method that you can call by K.method, but it will become an instance > method of the class K, and that means that K was the current class at > the time of declaring the method, even though it was self at the same > time. I think you're over-complicating this by using instance_eval as your starting point and then describing the behavior of class definitions as an exception to a rule. Most of the purpose of class definition blocks is to define instance methods, so it's easier just to look at it that way directly. If anything, I'd look at instance_eval as having the exceptional behavior -- but really, there are so few different permutations that it's probably easiest just to learn them and not worry about which is the rule and which the exception. The only really weird one is the top level :-) David -- Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL Advancing with Rails January 19-22 Fort Lauderdale, FL * * Co-taught with Patrick Ewing! See http://www.rubypal.com for details and updates!