From: "David A. Black" Date: 2008-09-24T21:51:15+09:00 Subject: Re: understanding inheritance and class singleton methods Hi -- On Wed, 24 Sep 2008, Ittay Dror wrote: > Hi, > > I'll start with what I understand: > class Foo > class << self > def hi > puts 'HI' > end > end > end > > Creates an instance of a singleton class that has the method #hi. So Foo.hi > calls the method defined in the class of Foo -> the singleton class (which > inherits from Class) > > My question: > class Bar < Foo > end > > Bar.hi --> 'HI' > > It looks like two things are happening: 1. Bar points to Foo, so instances of > Bar lookup methods in Foo also. 2. The instance Bar has a class that inherits > from Foo's instance class. The singleton class of Foo is the superclass of the singleton class of Bar. Actually, this is broken in 1.8.6, but if you look at 1.8.2 (that's the earlier one I happen to have around) or 1.9, it works: >> class Object; def singleton_class; class << self; self; end; end; end => nil >> class C; end => nil >> class D < C; end => nil >> D.singleton_class.superclass == C.singleton_class => true That's why D can reach C's singleton (i.e., class) methods: D's lookup path includes its own singleton class, and that class's superclass. It's also why the word "singleton" is less of a perfect fit when classes are involved, since C's singleton methods are actually callable by another object. So sometimes a class's singleton class is referred to as a metaclass (which isn't a perfect fit either, but it marks the distinction). 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!